gpt4 book ai didi

java - onPause() 方法后对 TextView 的更改丢失

转载 作者:行者123 更新时间:2023-11-30 02:22:40 27 4
gpt4 key购买 nike

我有一个带有显示数字的简单 TextView 的 Activity 。使用按钮,我从数字中添加或删除值 1(以及从局部变量 int points);

问题是:

如果我将数字加 1 然后打开设置 Activity (在代码中我不调用 finish() 方法,因此主要 Activity 不调用 onDestroy() 方法),或者如果我按主页按钮,当我返回主 Activity 时,显示的数字(和 int 点变量)显示为它们从未更改过。

另一方面,如果我修改数字,然后将带有 Intent 的值传递给主要 Activity 的另一个副本,则值会正确存储,并且即使在按下后也会显示更改

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

// Set POINTS

Points = (TextView) findViewById(R.id.Points);

if( getIntent().getExtras() != null) //get intent
{
points = getIntent().getExtras().getInt("points");
Points.setText(String.valueOf(points));
}
else
{
points = Integer.parseInt((String)(Points.getText()));
}

MainActivity 中将 Intent 发送到另一个 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 发送到 Settings 的代码:

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));
}

最佳答案

您应该保留您的 TextViewonPause(); 并重新创建它 onResume();。这可以使用 SharedPreference 来完成,如下所示。

@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();
}

当你恢复你的Activity

@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);

}

关于java - onPause() 方法后对 TextView 的更改丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28262834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com