How to make a spinner populate another spinner?

2019-08-17 00:50发布

问题:

How would you go about making a spinner populate another spinner based on the first spinners selection?

So for example:

Spinner1 items are vegetarian or meat eater.

  <string-array name="spinnerarray_veg_meat">
    <item >Vegetarian</item>
    <item >Meat eater</item> 
   </string-array> 

Spinner2 would then need to display either vegetarian meal names or meat eater ones depending on spinner1's selection.

回答1:

To do this you'll have to set a OnItemSelectedListener on your first Spinner to populate the second Spinner programmatically.

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {

              if(position == 0) {
                   // Populate the Spinner2 with different values
              } else {
                   // Populate the Spinner2 with different values
              }

        }
        public void onNothingSelected(AdapterView<?> parent) {
            return;

        }
    });


回答2:

There are a number of ways to do it. One being, create an Array of meat items and one of vegetable items. In onItemSelected() of spinner1 set the adapter for spinner2 according to the position

Spinner Docs

This link has many useful functions and properties available to Spinners