在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();
以上是三种常用的设置全局变量的方式,根据具体的需求选择合适的方式来设置全局变量。