简体   繁体   English

Android Studio-在Java代码中使用XML ID

[英]Android Studio - Using XML id in the java code

I have this line of code 我有这行代码

adapter = ArrayAdapter.createFromResource(this,R.array.cars10, R.layout.teste);

where cars10 is an string array, but what happens is that I have 10 string arrays: cars1,cars2,cars3...and so on... 这里cars10是一个字符串数组,但是发生的是我有10个字符串数组:cars1,cars2,cars3 ...依此类推...

I'd like to know if I can do it in an easy way, for example 我想知道是否可以轻松地做到这一点,例如

for(int i=1;i<=10;i++)adapter[i] = ArrayAdapter.createFromResource(this,R.array.cars+"i", R.layout.teste);``

ps: I know it does not work, it's so you guys can understand what I mean. ps:我知道这是行不通的,所以你们可以理解我的意思。

Maybe try something like that: 也许尝试这样的事情:

<resources>
    <string-array name="carA">
        <item>1</item>
        <item>2</item>
    </string-array>

    <string-array name="carB">
        <item>3</item>
        <item>4</item>
    </string-array>

    <array name="myArrays">
        <item>@array/carA</item>
        <item>@array/carB</item>
    </array>
</resources>

 final TypedArray arr = getResources().obtainTypedArray(R.array.myArrays);
 final int arrayId= arr.getResourceId(0, 0); 

you then can use the arrayId 然后,您可以使用arrayId

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

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