在Activity A中有一个TextView。程序中使用Shared Preferences来把一个TextView 保存在Activity C中。
当加载 Activity A 或者 B时,不去Activity C如何从Activity C中获取TextView?
Activity A 现在用下面的方法来获取 TextView
Intent id = getIntent();
if (id.getCharSequenceExtra("idid") != null) {
final TextView setmsg = (TextView)findViewById(R.id.loginid2);
setmsg.setText(id.getCharSequenceExtra("idid"));
}
只有另一个 activity 使用 putExtra 来获取的话才能执行。
你可以在 Activity C 中使用 SharedPreference:
textview.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ActivityC.this);
SharedPreferences.Editor editor = pref.edit();
editor.putString("idid", ""+s);
editor.commit();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
在 Activity A onCreate 中:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ActivityA.this);
setmsg.setText(pref.getString("idid", "null"));
为什么要把TextView保存到sp文件,如果其他界面需要把这个TextView做成通用的,在其他的界面的布局文件xml做include操作不是更好。而且findViewById是在当前界面的布局文件区做索引操作,不明白为什么要保存TextView.