Search code examples
javaandroidkotlinmultilingual

Kotlin hardcoded String


I want to add multilingual support to my app using the Android Studio Translations editor. But it only supports .xml strings. I have some strings in data class and I use data class for making ArrayList. I really want to call these strings from .xml but I couldn't figure out how.

my data class:

data class Infodc (
        val id: Int,
        val header: String,
        val image: Int,
        val infoOne: String,
        val infoTwo: String
)

my list

object Constants{
    fun getInfo(): ArrayList<Infodc>{
        val infoList = ArrayList<Infodc>()

        val inf1 = Infodc(
            1, "header_str", R.drawable.image0,
            "string_1", "string_2")
        infoList.add(inf1)
        return infoList
    }
}

I tried R.string.string_header for header = "header_str" but that only show 10 digits, not the string itself.

After that, I tried getString but again I failed.


Solution

  • You can do it like this:

    class MainActivity : AppCompatActivity()
    {
        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val infodc = Infodc(
                1,
                R.string.header,
                R.drawable.ic_launcher_foreground,
                R.string.info_one,
                R.string.info_two,
                this
            )
    
            Log.d("MyTag", "$infodc") // D/MyTag: Infodc(id=1, header=Header, image=2131099744, infoOne=Info One, infoTwo=Info Two)
    
    
        }
    }
    
    data class Infodc(
        val id: Int,
        val header: String,
        val image: Int,
        val infoOne: String,
        val infoTwo: String
    )
    {
        constructor(
            id: Int,
            @StringRes header: Int,
            @DrawableRes image: Int,
            @StringRes infoOne: Int,
            @StringRes infoTwo: Int,
            context: Context
        ) : this(
            id,
            context.getString(header),
            image,
            context.getString(infoOne),
            context.getString(infoTwo)
        )
    }
    

    Now You can pass to a constructor id of String and image but as a class field You will get String


    Another way is to have a class that only contains an id of string and then when You want to use it use getString of that field.