获取viewmodel中的字符串资源

Sun*_*y13 1 android viewmodel kotlin rx-java

我需要在 TextView 中显示百分比值,例如“15 %”,我通过这种方式在 viewModel 中执行此操作,并且它有效:

                    perfusionIndexValue.postValue(
                        list.lastOrNull()?.perfusionIndex?.takeIf {
                            it != PerfusionIndex.NO_DATA
                        }?.value?.toString().orEmpty() + " %"
                    )
Run Code Online (Sandbox Code Playgroud)

但如果我用资源来做:

                    perfusionIndexValue.postValue(
                        list.lastOrNull()?.perfusionIndex?.takeIf {
                            it != PerfusionIndex.NO_DATA
                        }?.value?.toString().orEmpty() + Resources.getSystem().getString(R.string.pi_percent)
                    )
Run Code Online (Sandbox Code Playgroud)

我明白了

io.reactivex.rxjava3.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | android.content.res.Resources$NotFoundException: String resource ID #0x7f0e0081
Run Code Online (Sandbox Code Playgroud)

我如何设置像“15%”这样的文本

Dươ*_*inh 6

就你而言,我认为你需要这里上下文。

但是,Fragment 或 Activity 的上下文不应传递到 ViewModel 中。仅使用 Application Context 来获取资源,...或 ViewModel 中与 Application 相关的内容。

在这里,如果您不使用 Hilt(或 Dagger),那么您应该替换ViewModel()AndroidViewModel(application)如下:

class MyViewModel(application: Application): AndroidViewModel(application) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果使用 Hilt,您可以通过@ApplicationContext如下注释注入应用程序上下文,而无需扩展AndroidViewModel()

@HiltViewModel
class MyViewModel @Inject constructor(
    @ApplicationContext private val context: Context
): ViewModel() {

}
Run Code Online (Sandbox Code Playgroud)

这里我注意到当使用 Hilt 将 Application Context 注入到 ViewModel 中时。将应用程序上下文注入 ViewModel 时,您将看到有关内存泄漏的警告。这是最近的Hilt版本中的警告,但我测试了Profiler,没有泄漏。

您可以通过调用以下方式在 ViewModel 中以字符串资源形式获取资源:

val myText = context.getString(R.string.your_string_id)
Run Code Online (Sandbox Code Playgroud)