Search code examples
androidspinnerlistener

set onClickListener for spinner item?


I have spinner which populates from database:

catSpinner = (Spinner) findViewById(R.id.spinner1);
cursor = dataAdapter.getAllCategory();
startManagingCursor(cursor);
String[] from = new String[] { DataAdapter.CATEGORY_COL_NAME };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter catAdapter = new SimpleCursorAdapter(this,  
           android.R.layout.simple_spinner_dropdown_item, cursor, from,to, 0);
catAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catAdapter.notifyDataSetChanged();
catSpinner.setAdapter(catAdapter);

And I want to call AlertDialog when I select last item(Add new category...).
After I added new category I want that "item(Add new category...)" was the last again.
How I can do this?


Solution

  • You SHOULD NOT call OnItemClickListener on a spinner. A Spinner does not support item click events. Calling this method will raise an Exception. Check this.

    You can apply OnItemSelectedListener instead.

    Edit :

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
    {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
        {
            String selectedItem = parent.getItemAtPosition(position).toString();
            if(selectedItem.equals("Add new category"))
            {
                    // do your stuff
            }
        } // to close the onItemSelected
        public void onNothingSelected(AdapterView<?> parent) 
        {
    
        }           
    });
    

    As far as adding "Add new category" to the end of the list is concerned, I think you should better go for custom adapter in which after adding all your items, you can add that constant ("Add new category") to end of array so that it should come last always.