Change Spinner based on another Spinner Selection

后端 未结 2 2080
傲寒
傲寒 2021-01-15 02:15

I have string array which contains all the country names and another string array with respective country codes. I am setting the country names string to spinner. When I sel

2条回答
  •  长发绾君心
    2021-01-15 02:30

    String[] countries = {"INDIA","DUBAI","KSA"};
            String[] country_code = {"91","971","966"};
    
            final Spinner spinnerCountry = (Spinner)findViewById (R.id.spinnerCountry);
            final Spinner spinnerCountryCode = (Spinner) findViewById (R.id.spinnerCountryCode);
    
            ArrayAdapter countryAdapter =  new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,countries);
    
            ArrayAdapter countryCodeAdapter =  new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,country_code);
    
            spinnerCountry.setAdapter(countryAdapter);
            spinnerCountryCode.setAdapter(countryCodeAdapter);
            
            spinnerCountry.setOnItemSelectedListener(new OnItemSelectedListener() {
    
                @Override
                public void onItemSelected(AdapterView arg0, View arg1,int position, long arg3) {
                    spinnerCountryCode.setSelection(position);
                }
    
                @Override
                public void onNothingSelected(AdapterView arg0) {
                    
                }
                
            });
            
            spinnerCountryCode.setOnItemSelectedListener(new OnItemSelectedListener() {
    
                @Override
                public void onItemSelected(AdapterView arg0, View arg1,int position, long arg3) {
                    
                    spinnerCountry.setSelection(position);
                }
    
                @Override
                public void onNothingSelected(AdapterView arg0) {
                    
                }
                
            });
    

    Here is some code that may fix your problem.

    Explanation:

    Assuming you have two spinners R.id.spinnerCountry and R.id.spinnerCountryCode.

    As you can see i created two arrays which contains countryName and countryCode respectively.

    Work Flow:-

    When i select one item in a Spinner then the other spinner loads with another item corresponding to the position.

    The code is Self-Explanatory!

提交回复
热议问题