Get index of array element based on value

I have a string array defined in arrays.xml that references two lines in strings.xml:

<string-array name="my_options">
  <item>@string/my_string_one</item>
  <item>@string/my_string_two</item>
</string-array>

<string name="my_string_one">Value 1</string>
<string name="my_string_two">Value 2</string>

I need to get the position of an element in an array based on the value of a string. The line Ie “Value 2” has an index of 1. I can obviously just hardcode the positional values ​​(0, 1, etc.), but it will break if the order of the lines is changed. I want the code to be positionally independent. The following works:

int value = Arrays.asList((getResources().getStringArray(R.array.my_options))).indexOf(getString(R.string.my_string_one));

Is there a more compact and easy way to do this?

+5
source share
2 answers

The code you show in your question is basically what you need to do.

, : Refactor Arrays.asList((getResources(). GetStringArray (R.array.my_options))) ( , , () ).

static List<String> myOptions;

.... 
    if (myOptions == null) {
        myOptions = Arrays.asList((getResources().getStringArray(R.array.my_options)));
    }

...

    int value = myOptions.indexOf(getString(R.string.my_string_one));
+7

, HashSet - , . .

0

All Articles