【发布时间】:2021-10-02 08:21:15
【问题描述】:
我目前正在使用绑定来动态设置使用 android 视图模型的各种文本视图的文本。目前,视图模型看起来像这样:
class MyViewModel(
resources: Resources,
remoteClientModel: Model = Model()
) : ObservableViewModel() {
init {
observe(remoteClientModel.liveData) {
notifyChange()
}
fun getTextViewTitle(): String = when {
someComplicatedExpression -> resources.getString(R.string.some_string, null)
else -> resources.getString(R.string.some_other_string)
}
}
还有xml布局:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="android.view.View"/>
<variable
name="viewModel"
type="my.app.signature.MyViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.textViewTitle}"
android:textAlignment="center"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
但是我想删除注入到视图模型中的“资源:资源”,因为资源与活动耦合。代码现在只返回字符串资源 id:
fun getTextViewTitle(): Int = when {
someComplicatedExpression -> R.string.some_string
else -> R.string.some_other_string
}
因此我删除了活动依赖项。编译器认为这很好,但它在运行时崩溃并出现以下异常:android.content.res.Resources$NotFoundException: String resource ID #0x0。
当尝试使用以下方法将 lifeCycleOwner 附加到绑定时会发生这种情况:
override fun onActivityCreated(savedInstanceState: Bundle?) {
// Some more code....
binding.lifecycleOwner = activity
// Some more code....
我不知道如何从视图模型中删除资源依赖关系,而不会让它在运行时崩溃。
编辑:
澄清一下:我的示例中的 ObservableViewModel 与此处找到的完全相同:
https://developer.android.com/topic/libraries/data-binding/architecture
用于执行notifyChange。
【问题讨论】:
-
我认为您的应用程序因此而崩溃
constructor of your ViewModel从构造函数中删除依赖项。如果您想使用ViewModel中的资源,请使用AndroidViewModel。 -
AndroidViewModel 有一个与注入不兼容的条件:“应用程序上下文感知 ViewModel。子类必须有一个接受 Application 作为唯一参数的构造函数。”就我而言,我无法使用 AndroidViewModel,因为我想注入执行 IO 任务的模型。
-
错误是因为它试图将
0(整数)设置为textview资源id。您应该重新检查并确保getTextViewTitle()不返回 0。