how to use spinner

2020-02-28 04:18发布

问题:

I am very new to android. I want to use 2 spinners in my application, one shows the countries list, when any country is selected the other spinner should show the list of cities of that country. when city is selected some action is performed. plz help me with some sample code. thanks in anticipation

回答1:

Here is something what we can use to add options to spinner2 w.r.t to spinner 1.

public class Activity extends Activity implements View.OnClickListener
{
    private Spinner spinner0, spinner1, spinner2, spinner3;
    private Button submit, cancel;

    private String country[], state[], city[], area[];

    Australia aus = new Australia();

    Object object;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        spinner0 = (Spinner)findViewById(R.id.spinnerCountry);
        spinner1 = (Spinner)findViewById(R.id.spinnerQ1);
        spinner2 = (Spinner)findViewById(R.id.spinnerQ2);
        spinner3 = (Spinner)findViewById(R.id.spinnerQ3);

        submit = (Button)findViewById(R.id.btnSubmit);
        cancel = (Button)findViewById(R.id.btnCancel);

        submit.setOnClickListener(this);
        cancel.setOnClickListener(this);

        country = new String[] {"Select Country", "Australia", "USA", "UK", "New Zealand", "EU", "Europe", "China", "Hong Kong",
                                "India", "Malaysia", "Canada", "International", "Asia", "Africa"};


        ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, country);
        adapter0.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner0.setAdapter(adapter0);
        Log.i("AAA","spinner0");

        spinner0.setOnItemSelectedListener(new OnItemSelectedListener()
        {           
            @Override
            public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id)
            {
                Log.i("AAA","OnItemSelected");
                int loc;
                loc = pos;

                switch (loc)
                {
                case 1:

                    state = aus.getState();
                    object = aus;

                    Log.i("AAA","ArrayAdapter1");                   
                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, state);
                    adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                    spinner1.setAdapter(adapter1);          Log.i("AAA","spinner1");
                    break;

                default:
                    Log.i("AAA","default 0");
                    break;
                }                               
            }       

            @Override
            public void onNothingSelected(AdapterView<?> arg1)
            {
                Log.i("AAA","Nothing S0");

            }
        });

       spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
       {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id) 
            {
                Log.i("AAA","OnItemSelected S1");
                int loc = pos;
                switch(loc)
                {
                    case 1:
                        Log.i("AAA","Australia");
                        if(object.equals(aus))
                        {
                            city = aus.getType(loc);
                        }
                        else
                        {
                            break;
                        }


                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, city);
                        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                        spinner2.setAdapter(adapter);           Log.i("AAA","spinner2");
                        break;

                    default:
                            Log.i("AAA", "default 1");
                        break;

                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {
                Log.i("AAA","Nothing S1");              
            }

        }); 

       spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
       {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long id)
        {
            int loc = pos;
            switch (loc)
            {
            case 1:
                if(object.equals(aus))
                {
                    area = aus.getTitle(loc);
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, area);
                adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                spinner3.setAdapter(adapter);           Log.i("","spinner3");               
                break;

            default:
                break;
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) 
        {
            // TODO Auto-generated method stub          
        }
       });

    }// on-create


    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
        case R.id.btnSubmit:

            break;

        case R.id.btnCancel:
            finish();
            break;

        default:
            break;
        }       
    }   
}

If you find this useful, then do give it up vote, so that others can find a good answer easily.

For each Country, you have to create a class for it, to just add State, City & Area. So that it doesn't become a mesh at a single at single page.

Have fun.

Regards,

Haps.



回答2:

Here is a sample code which depicts the usage of spinner and action performed when spinner item is selected

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

    Spinner spin;
    String spin_val;
    String[] gender = { "Male", "Female" };//array of strings used to populate the spinner
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//setting layout
        spin = (Spinner) findViewById(R.id.spinner_id);//fetching view's id
        //Register a callback to be invoked when an item in this AdapterView has been selected
        spin.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) { 
                // TODO Auto-generated method stub
                spin_val = gender[position];//saving the value selected


            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }

        });
      //setting array adaptors to spinners 
      //ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects
        ArrayAdapter<String> spin_adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, gender);

        // setting adapteers to spinners
        spin.setAdapter(spin_adapter);
    }


}

To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.You can also download & refer to the complete spinner_demo example project for better understanding.



回答3:

Check the following examples :

https://developer.android.com/guide/tutorials/views/hello-spinner.html
http://www.designerandroid.com/?cat=4



回答4:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spinner = (Spinner)findViewById(R.id.spinner);
    list = new ArrayList<String>();
    list.add("Select your Favorite Color");
    list.add("Blue");
    list.add("White");
    list.add("Red");
    list.add("Green");
    list.add("Black");
    list.add("Yellow");
    list.add("Pink");
    list.add("Orange");
    SpinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list){
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           View v = super.getView(position, convertView, parent);
            // set the textColor you want
            return v;
        }

        @Override
        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View v = super.getDropDownView(position, convertView, parent);
// Set the BackgroundColor
            return v;
        }
    };
    SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(SpinnerAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String state = adapterView.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
}

}