简体   繁体   中英

How to use a spinner item

I would like to have a certain action when a specific item is selected (eg item 2), but have a generic action occur for any others (eg items 1, 3, 4).

This is my code:

    private String[] array_spinner = new String[4];
    private thetiki mContext;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.main2);

        array_spinner[0] = "Mathimatika Genikis Paideias";
        array_spinner[1] = "Fusiki Genikis Paideias";
        array_spinner[2] = "Istoria Genikis Paideias";
        array_spinner[3] = "Viologia Genikis Paideias";

        Spinner s = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter adapter = 
            new ArrayAdapter(this, android.R.layout.simple_spinner_item, 
                array_spinner);
        s.setAdapter(adapter);

        // more code
   apostoli.setOnClickListener(new OnClickListener() {

                private AlertDialog show;

                public void onClick(View arg0) {

if (...) {


        if (array_spinner[2] != null) {
            //do something  

        } else if (array_spinner[0] != null || array_spinner[1] != null || array_spinner[3] != null) {

            //do something else
        }
    }

array_spinner[index] will never be null in this case. You've already initialized them, how could they be? You need to set up a listener to handle selections in the Spinner, something like this:

s.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(pos == 2) {
            //do specific action
        } else {
            //do generic action
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        //do nothing
    }
});

See more information in the Spinner tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM