在视图之间切换时,计数器变量未更新

时间:2019-01-31 21:49:04

标签: android-studio

我正在尝试创建一个计数器,该计数器在您每次返回主视图时都会更新。唯一的问题是,每次我回到主视图时,计数器都会重置为1。

package com.example.usingintent2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private int counter = 0;
    Button btn;
    TextView txv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txv = (TextView) findViewById(R.id.counterText);
    }
    public void onClick(View view) {
        startActivity(new Intent("com.example.usingintent2.SecondActivity"));
        counter++;
        txv = (TextView) findViewById(R.id.counterText);
        txv.setText(Integer.toString(counter));
    }
    public void onStart(){
        super.onStart();
        counter++;
        txv = (TextView) findViewById(R.id.counterText);
        txv.setText(Integer.toString(counter));
    }
    public void onResume(){
        super.onResume();
        counter++;
        txv.setText(Integer.toString(counter));
    }


}

1 个答案:

答案 0 :(得分:0)

您必须使用saveInstanceState捆绑包保存您的价值。

  public TextView txv;
  private static final String KEY_USERENTRY = "KEY_USERENTRY";
  private int counter;


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

txv = (TextView) findViewById(R.id.textView);
txv.setText(Integer.toString(counter));
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(KEY_USERENTRY, yourvalue);


}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    counter = savedInstanceState.getInt(KEY_USERENTRY);


}
}

yourvalue是您要保存的值。