N
N
nohchiadam2019-07-30 19:25:39
Java
nohchiadam, 2019-07-30 19:25:39

How to iterate over resources using a loop?

My task is to populate the RecylerView .

for (int i = 0; i < 11; i++) {
                switch (i) {
                    case 1:
                        items.add(new Send( R.string.adamt1));
                        break;
                    case 2:
                        items.add(new Send2( R.string.adama1,R.string.adama1t));
                        break;
                    case 3:
                        items.add(new Send(R.string.adam2));
                        break;
                    case 4:
                        items.add(new Send2( R.string.adama2,R.string.adama2t));
                        break;
                    case 5:
                        items.add(new Send( R.string.adamt3));
                        break;
                    case 6:
                        items.add(new Send2( R.string.adamta3,R.string.adamta3t));
                        break;

and so about 30 items.
The strings name differs only by a digit.
Is it possible to loop through all this somehow? So as not to write a lot of code?
And how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alexandrov, 2019-07-30
@nohchiadam

Upikay resources in an array, read a cycle.

<resources>  
<string-array name="myStringsArray">  
    <item>adamt1</item>  
    <item>adama1</item>  
    <item>adama1t</item>  
    <item>adam2</item>  
    <item>adama2</item>
    <item>adama2t</item>
</string-array>


....
String[] myStringsArray= getResources().getStringArray(R.array.myStringsArray);
for (int i = 0; i < 11; i+=3) {
             items.add(new Send( myStringsArray[i]));
             items.add(new Send2( myStringsArray[i+1],myStringsArray[i+2]));
}

S
Sergey Gornostaev, 2019-07-30
@sergey-gornostaev

Resources resources = context.getResources();
for (int i = 1; i <= 30; i++) {
    int resId = resources.getIdentifier("adamt" + i, "string", context.getPackageName());
}

But not sure if this is the most appropriate solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question