简体   繁体   English

如何在 ViewModel 中使用 Strings.xml 而不在 Android 中使用上下文?

[英]How to use Strings.xml in ViewModel without using context in Android?

We have existing app, we need to add Multiple Language Support for that app.我们有现有的应用程序,我们需要为该应用程序添加多语言支持。 All the strings which are accessed with String.xml are translating.使用 String.xml 访问的所有字符串都在翻译。 but we have a constants (which are strings), which we are accessing in VewModel.但是我们有一个常量(它们是字符串),我们在 VewModel 中访问它。 these constant are not getting translate.code structure is like below这些常数没有得到翻译。代码结构如下

Constant.kt file常量.kt 文件

    class Constants private constructor() {

companion object {

    const val NAME= "Name"
    const val LAST_NAME= "Last name"
    
}

ViewModel looks like this ViewModel 看起来像这样

VewModel.kt模型模型.kt

 class VewModel() : ViewModel() {
    fun getStrings():String{
        return NAME+LAST_NAME
    }
}

In Activity calling method like this在这样的Activity调用方法中

viewmodel.getStrings()

and there are relevant strings of Name and Last_Name in all multiple Strings.xml file.所有多个Strings.xml文件中都有Name和Last_Name的相关字符串。

I am not getting How do i convert those constant strings to multiple languages.我没有得到如何将这些常量字符串转换为多种语言。 I cant use context in viewmodel and constants(Architecture restrictions).我不能在视图模型和常量中使用上下文(架构限制)。 any help.任何帮助。

Either you use binding expression in your xml layout, for example the text:您可以在 xml 布局中使用绑定表达式,例如文本:

android:text="@{@string/name_label + `: ` + viewModel.name}"    //not single quote, be careful

Or use AndroidViewModel :或使用AndroidViewModel

class StudentViewModel(private val application: Application) : AndroidViewModel(application) {
    val name = "Sam"

    fun getNameText() = "${application.getString(R.string.name_label): $name}"

The way you pass arguement to ViewModel is through the ViewModelFactory , just boilerplate code:您将争论传递给ViewModel的方式是通过ViewModelFactory ,只是样板代码:

class StudentViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(StudentViewModel::class.java)) {
            return StudentViewModel(application) as T
        }

        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

And setup both in your fragment :并在您的fragment中进行设置:

viewModelFactory = StudentViewModelFactory( requireActivity().application)
viewModel = ViewModelProvider(this, viewModelFactory).get(StudentViewModel::class.java)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM