当屏幕方向改变时如何保持价值

3

我正在开发一个基础的Android应用,每当我点击按钮时,它会在TextView中加上一个数字。使用onSaveInstanceState()onRestoreInstanceState()函数,TextView中显示的数字也会在手机旋转时保留下来。

问题在于,当手机旋转后,数值被保留下来,但是当再次按下按钮后,它又从0开始计数,而不是从保存的值开始计数。

我的代码:

public class MainActivity extends AppCompatActivity {

    TextView showValue;
    int counter=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showValue = (TextView) findViewById(R.id.CounterValue);
    }


    public void countIN(View view)
    {
        counter++;
        showValue.setText(Integer.toString(counter));
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("my_text", showValue.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        showValue.setText(savedInstanceState.getString("my_text"));
    }
 }

感谢您的回复。

您的计数器在屏幕方向更改后仍保持为0。 - Basi
2个回答

1
你可以使用几种方法来保存和获取数据。 第一种 如果你的数据很小,那么可以使用 onSavedInstanceStateonRestoreInstanceState .. 有关详细信息,请参阅 this answerthis one 第二种 如果有过多的数据需要存储,则应改用 ViewModel; this 是一个可以入门的教程。

1

添加

counter=Integer.parseInt(savedInstanceState.getString("my_text"));

在onRestoreInstanceState方法内部。
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    showValue.setText(savedInstanceState.getString("my_text"));
    counter=Integer.parseInt(savedInstanceState.getString("my_text"));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接