在我的应用程序中,我让用户选择要显示的名称。它应该显示为:你好,usertext
!
我可以成功更新设置。我使用了偏好活动。我也可以更改值。但要更改所选文本视图中的文本,我必须重新启动应用程序。
如何在用户更新设置中的值后立即更新文本视图?
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Code goes here
return true;
}
};
EditTextPreference pref = (EditTextPreference)findPreference(getString(R.string.pref1));
pref1.setOnPreferenceChangeListener(changeListener);
EditTextPreference pref2 = (EditTextPreference)findPreference(getString(R.string.pref2));
pref2.setOnPreferenceChangeListener(changeListener);
您可以使用SharedPreferences,但不要忘记在设置值后使用.apply。这里有一个例子(不要忘记更改值以匹配您的editText、按钮、类等(:
活动二(输入新值并保存(:
public class settings extends MainActivity {
private Button mButton;
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
mButton = (Button) findViewById(R.id.submit);
mEditText = (EditText) findViewById(R.id.editTxtUsername);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = pref.edit();
if (mEditText.getText().length() > 0) {
editor.putString("username", mEditText.getText().toString());
editor.apply();
} else Toast.makeText(getApplicationContext(), "Please enter a valid username.", Toast.LENGTH_LONG).show();
}
});
}
}
活动一(要查看用户名的位置(:
public class MainActivity extends AppCompatActivity {
private TextView mTxtUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxtUsername = (TextView) findViewById(R.id.txtUsername);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
String username = pref.getString("username", "");
mTxtUsername.setText(username);
}
}
这应该有效,并将为他们下次打开应用程序保存价值!如果你对代码有任何问题,请告诉我,我刚刚启动了快速