在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;
這些方法可以根據具體需求選擇合適的方式來創建全局變量。