在Android中创建全局变量可以通过以下几种方式实现:
public class MyApplication extends Application {
private String globalVariable;
public String getGlobalVariable() {
return globalVariable;
}
public void setGlobalVariable(String globalVariable) {
this.globalVariable = globalVariable;
}
}
在AndroidManifest.xml中注册Application类:
<application
android:name=".MyApplication"
...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("globalVariable", "value");
editor.apply();
String globalVariable = preferences.getString("globalVariable", "");
public class GlobalVariable {
public static String globalVariable;
}
GlobalVariable.globalVariable = "value";
String value = GlobalVariable.globalVariable;
这些方法可以根据具体需求选择合适的方式来创建全局变量。