在Android中,可以通過以下幾種方式來設置全局變量:
public class MyApp extends Application {
private String globalVariable;
public String getGlobalVariable() {
return globalVariable;
}
public void setGlobalVariable(String globalVariable) {
this.globalVariable = globalVariable;
}
}
SharedPreferences sharedPrefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("globalVariable", "value");
editor.apply();
在其他地方獲取全局變量時,可以通過以下方式讀取:
SharedPreferences sharedPrefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String globalVariable = sharedPrefs.getString("globalVariable", "");
public class GlobalVariable {
private static GlobalVariable instance;
private String globalVariable;
private GlobalVariable() {}
public static GlobalVariable getInstance() {
if (instance == null) {
instance = new GlobalVariable();
}
return instance;
}
public String getGlobalVariable() {
return globalVariable;
}
public void setGlobalVariable(String globalVariable) {
this.globalVariable = globalVariable;
}
}
在其他地方獲取全局變量時,可以通過以下方式調用:
String globalVariable = GlobalVariable.getInstance().getGlobalVariable();
以上是三種常用的設置全局變量的方式,根據具體的需求選擇合適的方式來設置全局變量。