这个应用程序中有一个edittext,这个应用程序的目的是,当用户在edittext中写入文本或任何String时,用户关闭应用程序并重新打开它后,文本会保存在sharedPreferences中,并且文本会再次出现在该领域。或者存在相同的编辑文本,并且用户可以编写其文本的延续 但通常情况下,当程序关闭时,用户写入的所有文本都会被删除
MainActivity.kt:
class MainActivity : AppCompatActivity() {
lateinit var editText:EditText
private val name = "MY_TEXT"
private val key = "myStoredData"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText = findViewById(R.id.editTextText)
}
override fun onResume() {
super.onResume()
var sharedPref:SharedPreferences = getSharedPreferences(name, MODE_PRIVATE)
var myValue = sharedPref.getString(key,"")
editText.setText(myValue)
}
override fun onDestroy() {
super.onDestroy()
var sharedPref:SharedPreferences = getSharedPreferences(name, MODE_PRIVATE)
var edit = sharedPref.edit()
edit.putString(key,editText.text.toString())
edit.apply()
}
}
Activity_main.xml:
<EditText
android:hint="test"
android:id="@+id/editTextText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
谢谢你帮助我
编辑文本初始化后,将 onResume 代码放入 onCreate 中。以及 onStop 中放入的 onDestroy 代码。