onRestoreInstanceState()不是恢复值

时间:2017-02-02 07:32:57

标签: android performance

我希望恢复finalText的值,并在设备轮换时在TextView显示,但finalText未恢复其值。我已为finalText设置了默认值,以检查是否显示。 finalTextonActivityResult()中的变量,因此我想恢复其他活动产生的值。

public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final String REQUEST_RESULT = "REQUEST_RESULT";
public static final String KEY_COUNTER = "COUNTER";
private String finalText = "Default";

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

public void onClick(View view){
    Intent intent = new Intent(this, secondActivity.class);
    EditText editText = (EditText) findViewById(R.id.text);
    String text = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, text);
    startActivityForResult(intent, 2);
}

@Override
protected void onActivityResult(int comingFrom, int resultCode, Intent data){
    super.onActivityResult(comingFrom, resultCode, data);
    if (resultCode == RESULT_OK){
        TextView textView = (TextView) findViewById(R.id.textView1);
        finalText = Integer.toString(comingFrom) + Integer.toString(data.getIntExtra(REQUEST_RESULT, 0)) + resultCode;
        textView.setText(finalText);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    outState.putString(KEY_COUNTER, finalText);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
    super.onRestoreInstanceState(savedInstanceState);
    finalText = savedInstanceState.getString(KEY_COUNTER);
}

1 个答案:

答案 0 :(得分:0)

试试这个

TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  finalText = savedInstanceState.getString(KEY_COUNTER);
  textView = (TextView) findViewById(R.id.textView1);
  textView.setText(finalText);
}

@Override
protected void onActivityResult(int comingFrom, int resultCode, Intent data){
  super.onActivityResult(comingFrom, resultCode, data);
  if (resultCode == RESULT_OK){
    finalText = Integer.toString(comingFrom) + Integer.toString(data.getIntExtra(REQUEST_RESULT, 0)) + resultCode;
    textView.setText(finalText);
  }
}