post list

2015년 8월 13일

[Android] Preference

Context.getSharedPreference() : 응용프로그램 간에 서로 공유할 수 있다.
저장되는 데이터는 다음의 경로에 저장된다.

/data/data/com.your.package/shared_prefs/com.your.package_preferences.xml

반면 Activity.getPreference() 는 해당 어플리케이션만 사용할 수 있다.



예제 코드

public class MainActivity extends Activity {

private EditText edit;
private Button btn;

@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

edit = (EditText) findViewById(R.id.editText1);
edit.setOnKeyListener(new View.OnKeyListener() {

@Override public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Toast.makeText(MainActivity.this, edit.getText().toString(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});

btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ModifyText.class);
startActivity(intent);
}
});
}

@Override protected void onPause() {
super.onPause();
SharedPreferences setting = getSharedPreferences("mysetting", MODE_PRIVATE);
// SharedPreferences setting = getPreferences(MODE_PRIVATE);
Editor editor = setting.edit();
editor.putString("mytext", edit.getText().toString());
editor.commit();
}

@Override protected void onResume() {
super.onResume();
SharedPreferences setting = getSharedPreferences("mysetting", MODE_PRIVATE);
// SharedPreferences setting = getPreferences(MODE_PRIVATE);
edit.setText(setting.getString("mytext", ""));
}
}

댓글 없음:

댓글 쓰기