我做了一个小项目,我尝试使用共享首选项从编辑文本中更改名称。这是我的代码
SharePreferenceOwnActivity.java
public class SharePreferenceOwnActivity extends Activity {
Button b1;
TextView t1;
/** Called when the activity is first created. */@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.b1);
t1 = (TextView) findViewById(R.id.t1);
LoadPreferences();
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
Intent intent = new Intent().setClass(SharePreferenceOwnActivity.this, SharepreferenceActivity.class);
startActivity(intent);
}
});
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
t1.setText(strSavedMem1);
}
}
SharepreferenceActivity.java
public class SharepreferenceActivity extends Activity {
EditText e1;
Button b2;
/** Called when the activity is first created. */@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
e1 = (EditText) findViewById(R.id.e1);
b2 = (Button) findViewById(R.id.b2);
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SavePreferences("MEM1", e1.getText().toString());
Intent intent = new Intent().setClass(SharepreferenceActivity.this, SharePreferenceOwnActivity.class);
startActivity(intent);
}
});
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
此处编辑文本不会更改文本视图。:(为什么?我没有得到错误