1. MainActivity:
1 package com.example.activitycircledemo; 2 3 import androidx.annotation.Nullable; 4 import androidx.appcompat.app.AppCompatActivity; 5 6 import android.content.SharedPreferences; 7 import android.os.Bundle; 8 import android.text.TextUtils; 9 import android.util.Log; 10 import android.view.View; 11 import android.widget.Button; 12 import android.widget.EditText; 13 import android.widget.Toast; 14 15 public class MainActivity extends AppCompatActivity { 16 17 private static final String TAG = "MainActivity"; 18 private static final String MSG_RECORD = "msg_record"; 19 private static final String RECORD_KEY = "msg"; 20 private Button mBtnSend; 21 private EditText mEditContent; 22 private SharedPreferences mSharedPreferences; 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 29 initView(); 30 31 initListener(); 32 33 // 恢复数据,将数据保存在msg_record文件内 34 mSharedPreferences = this.getSharedPreferences(MSG_RECORD, MODE_PRIVATE); 35 String record = mSharedPreferences.getString(RECORD_KEY, null); 36 if (!TextUtils.isEmpty(record)) { 37 mEditContent.setText(record); 38 } 39 40 } 41 42 private void initListener() { 43 mBtnSend.setOnClickListener(new View.OnClickListener() { 44 @Override 45 public void onClick(View view) { 46 // 获取到短信的内容 47 String content = mEditContent.getText().toString().trim(); 48 if (TextUtils.isEmpty(content)) { 49 Toast.makeText(MainActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show(); 50 return; 51 } 52 Log.d(TAG, "发送短信..." + content); 53 } 54 }); 55 } 56 57 private void initView() { 58 mEditContent = (EditText) this.findViewById(R.id.content); 59 mBtnSend = (Button) this.findViewById(R.id.send); 60 } 61 62 /** 63 * 用户退出程序后,将已经输入的数据进行保存 64 */ 65 @Override 66 protected void onDestroy() { 67 super.onDestroy(); 68 // 把数据保存到SharedPreferences 69 String content = mEditContent.getText().toString().trim(); 70 if (!TextUtils.isEmpty(content)) { 71 // 取得edit编辑后,将数据通过键值对保存到文件中 72 SharedPreferences.Editor edit = mSharedPreferences.edit(); 73 edit.putString(RECORD_KEY, content); 74 edit.commit(); 75 } 76 77 } 78 }
2. activity_main:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity" 8 android:orientation="vertical"> 9 10 <EditText 11 android:id="@+id/content" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:hint="请输入短信内容..."/> 15 16 <Button 17 android:id="@+id/send" 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:text="发送"/> 21 </LinearLayout>
第五章 Activity的生命周期onCreate和onDestory 2.9
原文:https://www.cnblogs.com/EndlessShw/p/15349428.html