0

没关系。显然我对 SavedState 应该做什么有错误的想法。把这个职位留在这里,这样我的愚蠢就会被保存很久。

一直在尝试使用 SavedStateModel 的 ViewModel 工作了很长时间。请告诉我我遗漏了一些完全明显的东西,我已经进行了一项非常基本的活动,但仍然无法解决。它会继续返回主屏幕并返回(尽管我猜这通常是 ViewModel 的事情),但在应用程序被杀死时不会。

这是压缩的 Android Studio 项目,很抱歉我一开始就没有提供它的愚蠢:https ://www.slasheethecow.com/code/MooSavedState.zip

编辑:而不必复制/粘贴所有这些我压缩了 Android Studio 项目。删除了一堆其他(更复杂的)活动等,但我很确定它仍然可以工作。

这是活动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'
}

我无计可施。有或没有蹄子的人都知道我做错了什么吗?

4

1 回答 1

2

reddit上发布了这个,显然我一开始就一直在抱怨错误的树,SavedState 显然不像我想的那样适合这个。

对任何花时间经历这一切的人感到抱歉!

于 2021-03-05T10:00:29.243 回答