我有两个活动,其中主要活动有一个TextView,可以在第二个活动的sharedPreference中更改。当用户想要改变或者"保存"字符串,它将其保存在SP文件中,并返回主活动。但是,TextView不会更改为新的并显示旧的。应用程序需要重新启动才能运行。
我的目标是在onResume系统上使用活动生命周期,但根本没有拿起新的字符串。
我问如何在保存/从第二个活动返回时更改TextView。 有问题的行是: checkboxmessage =(sp.getString(" checkboxdescr",""));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//
// sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
sp = getSharedPreferences("contactapp", 0);
// named preferences - get the default ones and finish with it
//SET TEXTS
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv = (TextView) findViewById(R.id.sexycheckbox);
tv.setText(checkboxtext);
CheckBox cb = (CheckBox) findViewById(R.id.sexycheckbox);
////TOPCLEAR
TextView tt = (TextView)findViewById(R.id.toptext2);
tt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.edit_name);
EditText et2 = (EditText)findViewById(R.id.edit_number);
et.setText("");
et2.setText("");
CheckBox sexycheck;
sexycheck = (CheckBox)findViewById(R.id.sexycheckbox);
if (sexycheck.isChecked()) {
sexycheck.setChecked(false);
}
}
});
}
protected void onResume(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("contactapp", 0);
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv1 = (TextView) findViewById(R.id.sexycheckbox);
tv1.setText(checkboxtext);
}
答案 0 :(得分:1)
更改您的代码,看看它是否有效:
@Override
protected void onResume() {
super.onResume();
tv1.setText("new Text test");
}
答案 1 :(得分:1)
即使你复制粘贴,你仍然需要知道你应对的是什么。
替换这些行
super.onCreate(savedInstanceState); //You call wrong parent method here
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //you call this in onCreate already
setContentView(R.layout.activity_main); //you call this in onCreate already
sp = getSharedPreferences("contactapp", 0); //you call this in onCreate already
与
super.onResume(savedInstanceState);
在onResume()方法中。