2

I have strings.xml file like below:

<string-array name="planet">
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
</string-array>

My activity_main.xml code segment for my spinner:

<Spinner
   android:id="@+id/spinner"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"/>

My MainActivity.java code segment:

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.planet, android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

Now I want to do this code like below:

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    String arrayName = "planet";
    ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.arrayName, android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this); 

May I get the help that if it is possible then how to do this.

0

3 Answers 3

2

You can get Integer Id of String Array from string.xml like below Code .

String arrayName = "planet";
int arrayName_ID= getResources().getIdentifier(arrayName , "array",this.getPackageName()); 
// You had used "arrayName"
String[] items = getResources().getStringArray(arrayName_ID);
Sign up to request clarification or add additional context in comments.

Comments

1
String value = getResources().getStringArray(R.id.value_array)[selectedIndex];

and you get all String[] without specifying index.

Comments

0

You can use string array like

 ArrayList<String> string_array = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.string_array_name)));

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item,string_array);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.