【问题标题】:Changes to TextView lost after onPause() method在 onPause() 方法之后对 TextView 的更改丢失
【发布时间】:2015-02-01 12:42:17
【问题描述】:

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

问题是:

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

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

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

【问题讨论】:

  • 我不确定这是否会有所帮助,但您可以尝试将 Array 设为静态,以便在所有对象中保持相同...当然,如果您有多个对象,这将无法按预期工作一次活动的对象

标签: java android android-intent textview onpause


【解决方案1】:

您可以保留您的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);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2016-09-19
    • 1970-01-01
    • 2020-03-02
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多