无论我尝试什么,都无法让 ViewModel 上的 SavedState 正常工作
Just can't get SavedState on ViewModel working no matter what I try
没关系。显然我对 SavedState 应该做什么有错误的想法。把post留在这里,让我的愚蠢永远保存。
多年来一直在尝试使用 SavedStateModel 获取 ViewModel。请告诉我我遗漏了一些非常明显的东西,我已经下降到一个非常基本的 activity 但仍然无法解决。它会持续返回主屏幕并返回(虽然我猜这通常是 ViewModel 的事情)但当应用程序被杀死时不会。
这是压缩的 Android Studio 项目,很抱歉我的愚蠢没有首先提供它:https://www.slasheethecow.com/code/MooSavedState.zip
编辑: 不必 copy/paste 所有这些我压缩了 Android Studio 项目。删除了一堆其他(更复杂的)活动等,但我很确定它仍然有效。
这里是activity,CowSaved.kt:
package com.slasheethecow.moosavedstate
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
class CowSaved : AppCompatActivity() {
val cowModel: CowSavedModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cow_saved)
setStuffUp()
}
private fun setStuffUp() {
findViewById<Button>(R.id.cowSaved_submitButton).setOnClickListener {
cowModel.cowSetName(findViewById<EditText>(R.id.cowName_editText).text.toString())
}
cowModel.cowName.observe(this, {
findViewById<TextView>(R.id.cowSaved_displayView).text = "${resources.getString(R.string.cow_prefix)} $it" ?: ""
})
}
}
这是 ViewModel,CowSavedModel.kt:
package com.slasheethecow.moosavedstate
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
class CowSavedModel(private val myState: SavedStateHandle): ViewModel() {
companion object {
val KEY_NAME = "cow_saved_name_key"
}
val cowName: LiveData<String> = myState.getLiveData(KEY_NAME)
fun cowSetName(newname: String) {
myState.set(KEY_NAME, newname)
}
}
这些可能无关紧要,但这是布局,activity_cow_saved.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CowSaved">
<EditText
android:id="@+id/cowName_editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="48dp"
android:layout_marginRight="48dp"
android:ems="10"
android:hint="@string/cow_edittext_hint"
android:inputType="textPersonName"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/cowSaved_submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@string/cow_submit_button"
app:layout_constraintEnd_toEndOf="@+id/cowName_editText"
app:layout_constraintStart_toStartOf="@+id/cowName_editText"
app:layout_constraintTop_toBottomOf="@+id/cowName_editText" />
<TextView
android:id="@+id/cowSaved_displayView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="48dp"
android:layout_marginRight="48dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cowSaved_submitButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是相关的字符串,cow_strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cow_edittext_hint">Type in me! You know you want to.</string>
<string name="cow_submit_button">Do me first! Actually, nah.</string>
<string name="cow_prefix">Grats! You\'re a cow named: </string>
</resources>
这是它在清单中的声明方式,AndroidManifest.xml (duh):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.slasheethecow.moosavedstate">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MooSavedState">
<activity android:name=".CowSaved">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application
</manifest>
这里是 build.gradle(我可能在试图找到一个有效的依赖性方面做得太过分了):
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.slasheethecow.moosavedstate"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
implementation 'androidx.activity:activity-ktx:1.3.0-alpha02'
implementation 'androidx.fragment:fragment-ktx:1.3.0'
implementation 'androidx.savedstate:savedstate-ktx:1.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-core-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
我已经无计可施了。有没有蹄子的人知道我做错了什么吗?
在 reddit 上发布了这个,显然我一开始就一直在寻找错误的树,SavedState 显然不是我想的那样。
对所有花时间经历这件事的人表示抱歉!
没关系。显然我对 SavedState 应该做什么有错误的想法。把post留在这里,让我的愚蠢永远保存。
多年来一直在尝试使用 SavedStateModel 获取 ViewModel。请告诉我我遗漏了一些非常明显的东西,我已经下降到一个非常基本的 activity 但仍然无法解决。它会持续返回主屏幕并返回(虽然我猜这通常是 ViewModel 的事情)但当应用程序被杀死时不会。
这是压缩的 Android Studio 项目,很抱歉我的愚蠢没有首先提供它:https://www.slasheethecow.com/code/MooSavedState.zip
编辑: 不必 copy/paste 所有这些我压缩了 Android Studio 项目。删除了一堆其他(更复杂的)活动等,但我很确定它仍然有效。
这里是activity,CowSaved.kt:
package com.slasheethecow.moosavedstate
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
class CowSaved : AppCompatActivity() {
val cowModel: CowSavedModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cow_saved)
setStuffUp()
}
private fun setStuffUp() {
findViewById<Button>(R.id.cowSaved_submitButton).setOnClickListener {
cowModel.cowSetName(findViewById<EditText>(R.id.cowName_editText).text.toString())
}
cowModel.cowName.observe(this, {
findViewById<TextView>(R.id.cowSaved_displayView).text = "${resources.getString(R.string.cow_prefix)} $it" ?: ""
})
}
}
这是 ViewModel,CowSavedModel.kt:
package com.slasheethecow.moosavedstate
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
class CowSavedModel(private val myState: SavedStateHandle): ViewModel() {
companion object {
val KEY_NAME = "cow_saved_name_key"
}
val cowName: LiveData<String> = myState.getLiveData(KEY_NAME)
fun cowSetName(newname: String) {
myState.set(KEY_NAME, newname)
}
}
这些可能无关紧要,但这是布局,activity_cow_saved.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CowSaved">
<EditText
android:id="@+id/cowName_editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="48dp"
android:layout_marginRight="48dp"
android:ems="10"
android:hint="@string/cow_edittext_hint"
android:inputType="textPersonName"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/cowSaved_submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@string/cow_submit_button"
app:layout_constraintEnd_toEndOf="@+id/cowName_editText"
app:layout_constraintStart_toStartOf="@+id/cowName_editText"
app:layout_constraintTop_toBottomOf="@+id/cowName_editText" />
<TextView
android:id="@+id/cowSaved_displayView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="48dp"
android:layout_marginRight="48dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cowSaved_submitButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是相关的字符串,cow_strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cow_edittext_hint">Type in me! You know you want to.</string>
<string name="cow_submit_button">Do me first! Actually, nah.</string>
<string name="cow_prefix">Grats! You\'re a cow named: </string>
</resources>
这是它在清单中的声明方式,AndroidManifest.xml (duh):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.slasheethecow.moosavedstate">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MooSavedState">
<activity android:name=".CowSaved">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application
</manifest>
这里是 build.gradle(我可能在试图找到一个有效的依赖性方面做得太过分了):
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.slasheethecow.moosavedstate"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
implementation 'androidx.activity:activity-ktx:1.3.0-alpha02'
implementation 'androidx.fragment:fragment-ktx:1.3.0'
implementation 'androidx.savedstate:savedstate-ktx:1.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-core-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
我已经无计可施了。有没有蹄子的人知道我做错了什么吗?
在 reddit 上发布了这个,显然我一开始就一直在寻找错误的树,SavedState 显然不是我想的那样。
对所有花时间经历这件事的人表示抱歉!