更新两个activity之间的数据Android Java



我正在制作一款显示一系列视觉刺激的简单Android游戏。我有两个活动(Main &设置)。在设置中,您将能够编辑刺激的数量。当我编辑数字时,它不会在主活动中更新。

这是在主活动onCreate

settings = new SettingsActivity();
setNrOfStimuli = settings.getSetNrOfStimuli();
stimuli = new int[setNrOfStimuli];

这是在主活动

public void onSettingBtnClicked(View view) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
}

设置

public void onBackBtnClicked(View view) {
setNrOfStimuli = Integer.parseInt(inputNrOfStimuliView.getText().toString());
finish();
}

我可以通过Intent或getter &但问题是初始化时,它从设置返回到主活动。

我认为你应该使用SharedPreferences来存储用户的设置。您可以通过本教程了解它。https://www.javatpoint.com/android-preferences-example

你必须在教程的代码中修改:在prefs.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- you do not worry about how this information will be stored, it will be handled 
by  the android. You have to use those data by getting that data by their key -->
<EditTextPreference
android:key="stimuli_numbers"
android:summary="Please enter Number of stimuli"
android:inputType="numberDecimal"
android:digits="0123456789"
android:title="Number of stimuli" />
</PreferenceScreen>

Main Activity

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//get the number of stimuli
//stimuli_numbers is the key and 0 is the default value (you can change this according to yours.
setNrOfStimuli = Integer.valueOf(prefs.getString("stimuli_numbers","0");

最新更新