How to make a spinner populate another spinner?

2019-08-17 00:56发布

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.

2条回答
何必那么认真
2楼-- · 2019-08-17 01:37

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

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-17 01:43

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;

        }
    });
查看更多
登录 后发表回答