[英]How to retrieve boolean values from a different activity?
我有一個活動將各種變量設置為 true 或 false,用作其他活動的設置。 我需要能夠在我的其他活動中調用這些變量的狀態,但我不知道如何調用。 我知道我可以使用的字符串
getApplicationContext().getResources().getString(R.string.stringName);
但同樣的事情對布爾值不起作用。 有人建議使用
activityName.variableName
但這也行不通。 有什么建議?
而不是static
變量或application
變量使用SharedPreference
來實現這一點,這也會在應用程序關閉時持續存在。
設置Activity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("YOUR_KEY1", true);
editor.putBoolean("YOUR_KEY2", false);
editor.putBoolean("YOUR_KEY3", true);
editor.commit();
....
}
然后在其他活動或片段中使用getBoolean()
來檢索這些數據。
其他Activity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//here false is the default value if key is missing
boolean value1 = sharedPreferences.getBoolean("YOUR_KEY1", false);
boolean value2 = sharedPreferences.getBoolean("YOUR_KEY2", false);
boolean value3 = sharedPreferences.getBoolean("YOUR_KEY3", false);
....
}
您可以使用多種最常見的兩種方式制作全局變量
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
你可以從這里學習如何使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.