How to change the content of Spinners dynamically

2019-06-10 22:13发布

问题:

I have placed 4 spinners in a SlidingDrawer. And I have created a string-array in string.xml, like

<string-array name="colorArray">
        <item>Red</item>
        <item>Green</item>
        <item>Blue</item>
        <item>Orange</item>
        <item>While</item>
        <item>Black</item>
</string-array>

I want to populate the spinners with this array..

For that i had done like,

    option1 = (Spinner)findViewById(R.id.spinner_first);
    adapter = ArrayAdapter.createFromResource(getApplicationContext(), 
            R.array.colorArray, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    option1.setAdapter(adapter);

and the same for the other 3. It works fine for me now. Now the result is like, the entire array is listed on all the spinners.

But i want to remove the item selected by one spinner in all the other spinners, so that that item is not shown in the other 3.. For example, if i select "red" for the first spinner, the item "Red" must be removed from all other spinners..

How can that be achieved.

Sample codes and guidance will be appreciable.. Thanks in advance..

回答1:

just create the sub array of main array

like first fetch the array from xml file now by default 0th position as selected by default then skipped in sub array

String mainArr[]; // fetch from xml

String sub1[] = new String[mainArr.length-1];

now store the main array value into the sub1 array by iterating and in the get put the condition for storing the value if the selected position == i then skip or selected position!=i do this in item change listener to re create array from the main array with skipping the selected item and notify it by adapter



回答2:

In your onItemSelected() for the OnItemSelectedListener for the Spinner, you need to do the following for each one of the other Spinners:

Spinner spinner; // Each one of the other spinners
String item; // Item selected in the current spinner

// Get the adapter for the other spinner
ArrayAdapter<CharSequence> array = spinner.getAdapter();
// Remove selected element in the current spinner from adapter
array.remove(item);
// Set adapter again
spinner.setAdapter(array);

Sorry but I didn't (and can't) test it...