简体   繁体   中英

String-array in Kotlin

Begin new project in Kotlin and missing those.

Try to get string-array recources but can't.

In strings.xml I palced next items.

<string-array name="themeList">
    <item>white</item>
    <item>sepia</item>
    <item>black</item>
    <item>pink</item>
</string-array>

In code I try next:

val res: Resources = resources
val appThemeList = arrayOf(res.getStringArray(R.array.themeList))

for (value in appThemeList) {
    Log.i ("value", value.toString())
}

But in logCat i see:

I/value: [Ljava.lang.String;@40145f2

And I don'r understand, what I do incorrectly.

replace

val appThemeList = arrayOf(res.getStringArray(R.array.themeList))

to

val appThemeList = res.getStringArray(R.array.themeList)

In other case you got array

 val myArray = res.getStringArray(R.array.themeList) //already array

And added to another array

 arrayOf(myArray) // array of arrays

In android is depend on context when outside Activity like this

val themes = context.resources.getStringArray(R.array.themeList)

or without context is direct to resource when inside Activity

val themes = resources.getStringArray(R.array.themeList)

As we know res.getStringArray return arraylist so you do not need to write arrayOf on your code.

Simple way to achieve your goal is:-

val list = res.getStringArray(R.array.list);

We can use arrayOf when we have to define our array or we have already arraylist like below :-

val myArray = arrayOf(4, 5, 7, 3);

试试这个,

 val Lines = Arrays.asList(resources.getStringArray(R.array.list))

在 kotlin 中使用:

var yourVar = resources.getStringArray(R.array.your_string_array)

在 kotlin 中,还需要使用如下上下文

var arry = context.resources.getStringArray(R.array.your_string_array)

With this line of code you get exactly the element in the place of index.

val the_string = resources.getStringArray(R.array.YOUR_STRING_ARRAY)[index].toString()

This will be your res/values/strings.xml

<string-array name="YOUR_STRING_ARRAY">
    <item>kJ</item>
    <item>kWh</item>
    <item>Btu</item>
    <item>kcal</item>
</string-array>

As an example if the index is 1 then the return value is "kWh"

如果要使用RecyclerView.Adapter类中的资源路径,则必须将其放入函数onBindViewHolder

val myItem = holder.itemView.resources.getStringArray(R.array.myItem_string_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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