如何保存textView

时间:2016-04-25 02:41:10

标签: android android-studio-2.0

如何保存textView,以便在关闭并重新启动活动时文本仍然存在?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_current_homework);

    Intent intent = getIntent();
    String message = intent.getStringExtra(AddNewHomework.EXTRA_MESSAGE);
    TextView textView = (TextView) findViewById(R.id.textView99);
    textView.setText(message);

1 个答案:

答案 0 :(得分:0)

使用textView.getText()SharedPreference中的其他人onDestroy保存文字。然后在onCreate中阅读。

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
    super.onCreate(savedInstanceState, persistentState);
    setContentView(R.layout.main);
    //TODO initialization
    SharedPreferences preferences = getApplicationContext()//
            .getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE);
    mTextView.setText(preferences.getString("KEY_NAME",""));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    final String text = mTextView.getText();
    final SharedPreferences.Editor editor = getApplicationContext()//
            .getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE)//
            .edit();//
    editor.putString("KEY_NAME", text).commit();
}