gpt4 book ai didi

java - 重新加载共享首选项

转载 作者:行者123 更新时间:2023-12-02 04:21:40 25 4
gpt4 key购买 nike

我对 Android 编程很陌生,并且在理解 SharedPreferences 方面遇到问题。我有一个主要 Activity 和一个设置 Activity 。我希望能够在“设置 Activity ”中更改 SharedPreference(此处称为“firstWaitTime”)并在“主 Activity ”中使用它。我可以在设置中设置新值,但在主 Activity 中,我只有在关闭并重新打开应用程序时才能看到新值。

我想我需要一个 OnPrefrenceChanged Listener,但我不知道如何实现它......

主要部分如下所示:

public class MainActivity extends ActionBarActivity {

//Radio Button
private int stufe;

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


SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);

//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);

}

设置 Activity 如下所示:

 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);

final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);

//BUTTON

final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);

save.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();

//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));

//---saves the values---
editor.commit();

Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}

实现这一目标的最佳方法是什么?

最佳答案

onCreate() 将不会被调用,因为 Android 尚未终止 Activity。尝试将代码放入 onResume() 中。欲了解更多信息,请阅读the Android Activity lifecycle .

关于java - 重新加载共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32702981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com