我在我的 Android 应用程序中创建了两个 Activity 。
该变量在 Activity 1 中声明。现在我想使用该变量,同时更新 Activity 2 和 Activity 1 中的值。并且 Activity 应该使用该变量的最新值。
我想我们可以使用 Intents 来做到这一点,但我想知道任何其他更简单的方法。
最佳答案
您可以使用共享首选项
从共享首选项中检索数据
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
}
编辑共享首选项中的数据
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
关于java - 在两个 Activity 中共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208394/