Java onPause()方法之后对TextView的更改丢失

Java onPause()方法之后对TextView的更改丢失,java,android,android-intent,textview,onpause,Java,Android,Android Intent,Textview,Onpause,我有一个简单的文本视图显示一个数字的活动。 使用按钮,我从数字(和局部变量int points)中添加或删除值1 问题是: 如果我在数字上加1,然后打开“设置”活动(在代码中,我不调用finish()方法,因此主活动不调用onDestroy()方法),或者如果我按Home按钮,当我返回主活动时,所显示的数字(以及int points变量)将显示为从未更改过 另一方面,如果我修改了数字,然后有意将这些值传递给主活动的另一个副本,则会正确存储这些值,即使按了之后也会显示更改 mainActivity

我有一个简单的文本视图显示一个数字的活动。 使用按钮,我从数字(和局部变量int points)中添加或删除值1

问题是:

如果我在数字上加1,然后打开“设置”活动(在代码中,我不调用finish()方法,因此主活动不调用onDestroy()方法),或者如果我按Home按钮,当我返回主活动时,所显示的数字(以及int points变量)将显示为从未更改过

另一方面,如果我修改了数字,然后有意将这些值传递给主活动的另一个副本,则会正确存储这些值,即使按了之后也会显示更改

mainActivity中设置点的代码(在onResume()中)

MainActivity中向另一个MainActivity发送意图的代码:

Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("points", points);
startActivity(toMulti);
overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
finish();
MainActivity中向设置发送意图的代码:

Intent toSettings = new Intent(this, SettingsSingle.class);
startActivity(toSettings);
按钮代码:

 public void plus1(View view)
{
    points = Integer.parseInt((String)(Points.getText()));
    points = points + 1;
    Points.setText(String.valueOf(points));
}

您可以保存
TextView
value
onPause()并重新创建它
onResume()。这可以使用
SharedReference
完成,如下所示

@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

    String yourStringValues = yourTextView.getText().toString();

    // We need an Editor object to make preference changes.
    // All objects are from android.context.Context
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("yourKey", yourStringValue);

    // Commit the edits!
    editor.commit();
}
当您继续您的
活动时

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    String yourRetrievedStringValue = settings.getString("yourKey", "");
    TextView yourTextView = findViewById(R.id.yourTextViewId);
    yourTextView.setText(yourRetrievedStringValue);

}

我不确定这是否有帮助,但您可以尝试将数组设置为静态,以便在所有对象中保持不变。。。当然,若一次有多个对象处于活动状态,这将无法按预期工作
@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    String yourRetrievedStringValue = settings.getString("yourKey", "");
    TextView yourTextView = findViewById(R.id.yourTextViewId);
    yourTextView.setText(yourRetrievedStringValue);

}