1

I am translating an app in Kotlin using two different files of strings but in arrayListOf there are string like this:

var language = arrayListOf<String>(
    "Profile Settings",
    "About Us",
    "Rate Us",
    "Language",
    "Push Notification",
    "Terms of Service",
    "Privacy Policy",
    "Help (FAQ)",
    "Support"
)

i want to change it to be responsive to the language chosen for example:

var language = arrayListOf<String>(
    "@strings/Profile Settings",
    
)

is it possible to do it from arrayListOf? or there is another way to do it?

2 Answers 2

2

@string is XML syntax for a String resource. To access the String resources in Kotlin, you use R.string. The R values are Ints, so you need to convert them to Strings, which you can do using map to avoid having to repeat code for every element.

val language: List<String> = listOf(
    R.string.profileSettings,
    //...
).map { requireContext().getString(it) }

If you do this in a property instead of in a function, you need to wrap the whole declaration in by lazy because the context is not available until the Fragment is attached.

In an Activity, you can omit requireContext(). since the Activity itself is its own Context, so it can be shortened to .map(::getString).

Sign up to request clarification or add additional context in comments.

2 Comments

i keep getting this error "Unexpected tokens (use ';' to separate expressions on the same line)" after trying your solution
You must have a syntax issue. Maybe you used the wrong kind of brackets.
1

You can re-write the Array-list like this:

var language = arrayListOf<String>(
   getString(R.string.profile_settings),
   .... 
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.