我有一个活动将各种变量设置为true或false,以用作其他活动的设置。我需要能够在其他活动中调用这些变量的状态,但是我不知道怎么做。我知道可以使用的字符串
getApplicationContext().getResources().getString(R.string.stringName);
但是对于Boolean,同一件事将不起作用。建议有人使用
activityName.variableName
但是那也不行。有什么建议吗?
您可以使用很多最常见的两种方法来创建全局变量
[1-使用
Application
类
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
请确保不要在manifest
文件中声明
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
如何使用?
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
2- 通过使用
Extra
作为变量,借助Intent
将其从活动传递给其他人>]Intent intent = new Intent(getBaseContext(), SignoutActivity.class); intent.putExtra("EXTRA_SESSION_ID", sessionId); startActivity(intent);
要在第二活动中阅读,请使用
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
对于设置屏幕建议使用
SharedPreference
,您可以从here中学习如何使用
代替static
变量或application
变量,而使用SharedPreference
来实现这一点,该变量也将在应用程序关闭时持续存在。