离开 activity 时更改文本视图后保存实例状态

saving instance state after changing textview when leaving the activity

我在单击 Button 时出现 TimePickerDialog,并在 TextView 上显示我选择它的时间。当我离开 activity 回来时,textView 是空的。我想保存这个 textView

的状态

下面是TimePickerDialog.OnTimeSetListener的代码

private TimePickerDialog.OnTimeSetListener TimePickerListener =
        new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hour, int minute) {
                switch (timePickerInput) {
                    case R.id.set_sabah:
                        mCalen.set(Calendar.HOUR_OF_DAY, hour);
                        mCalen.set(Calendar.MINUTE, minute);
                        int hour12format = mCalen.get(Calendar.HOUR);
                        hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
                        minute = mCalen.get(Calendar.MINUTE);
                        ampm = mCalen.get(Calendar.AM_PM);
                        String ampmStr = (ampm == 0) ? "AM" : "PM";
                        s1 = "Time is set in " + hour12format + " : " + minute + " " + ampmStr;
                        Toast.makeText(getApplicationContext(),s1 , Toast.LENGTH_LONG).show();
                        txtS.setText(s1);

                        break;

                    case R.id.set_masaa:
                        mCalen.set(Calendar.HOUR_OF_DAY, hour);
                        mCalen.set(Calendar.MINUTE, minute);
                        int hour12format2 = mCalen.get(Calendar.HOUR);
                        hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
                        minute = mCalen.get(Calendar.MINUTE);
                        ampm = mCalen.get(Calendar.AM_PM);
                        String ampmStr2 = (ampm == 0) ? "AM" : "PM";
                        s2 = "Time is set in " + hour12format2 + " : " + minute + " " + ampmStr2;
                        Toast.makeText(getApplicationContext(),s2 , Toast.LENGTH_LONG).show();
                        txtM.setText(s2);
                        break;
                }
                setAlarm(mCalen);

            }

        };

我尝试通过以下代码保存实例状态

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    savedInstanceState.putString("savedS1", txtS.getText().toString());
    savedInstanceState.putString("savedS2", txtM.getText().toString());

以下是 onRestoreInstanceState

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    String s1 = savedInstanceState.getString("savedS1");
    String s2 = savedInstanceState.getString("savedS2");
    txtS.setText(s1);
    txtM.setText(s2);
}

我知道这个解决方案是错误的,但希望得到任何帮助。

那么如果你想在关闭 activity 后保存一个值的状态,那么你应该去共享首选项: http://developer.android.com/reference/android/content/SharedPreferences.html