set onClickListener for spinner item?
Asked Answered
F

2

38

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?

Fomalhaut answered 24/8, 2012 at 11:50 Comment(0)
M
103

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.

Muscatel answered 24/8, 2012 at 11:55 Comment(6)
I know this. But how I can handle in OnItemSelectedListener selected only one item?Fomalhaut
when u select any item, you will get what item u selected. Compare that selected item with your predefined item as it is constant. If selected item is that predefined item, do your taskMuscatel
It doesn't work. I think because this parent.getItemAtPosition(position).toString(); return position and convert it to string.Fomalhaut
It will return particular object at that position and convert it to string. It wont return position. For position or item Id, parent.getItemIdAtPosition(position) method is usedMuscatel
You've forgotten the "}" for onItemSelected(...)Tottering
Note crucial bit of information: onItemSelected will fire twice - on initialization and when selected by user manually. That means if your "// do your stuff" does some kind of initialization in code, you do not need to declare it elsewhere - spinner will call it automatically without user explicitly making a selection.Heir
F
7

Hook to OnItemClickListener of Spinner. Then check whether the selected item is "Add new category".

If yes, show the dialog to add the new item.

While adding the new item,

  1. Remove the last item "Add new category".
  2. Add the new category entered.
  3. Then Add the item "Add new category" again.

This will make the "Add new category" item as last one.

Code Sample :

layout main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >

<Spinner
    android:id="@+id/cmbNames"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

layout spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

Activity class :

public class MainActivity extends Activity {

private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";

private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;

private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        HashMap<String, String> map = lstNames.get(arg2);
        String name = map.get(NAME);
        if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
            lstNames.remove(map);
            counter++;
            addNewName(String.valueOf(counter));
            addNewName(ADD_NEW_ITEM);
            adapter.notifyDataSetChanged();
        }
    }

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

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    populateList();

    cmbNames = (Spinner) findViewById(R.id.cmbNames);
    adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
            new String[] { NAME }, new int[] { R.id.tvName });
    cmbNames.setAdapter(adapter);
    cmbNames.setOnItemSelectedListener(itemSelectedListener);
}

private void populateList() {
    lstNames = new ArrayList<HashMap<String, String>>();

    addNewName("abc");
    addNewName("pqr");
    addNewName("xyz");
    addNewName(ADD_NEW_ITEM);
}

private void addNewName(String name) {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put(NAME, name);
    lstNames.add(map);
}

}
Fulfill answered 24/8, 2012 at 11:55 Comment(1)
an onitemclicklistener cannot be hooked to a spinnerAngelita

© 2022 - 2024 — McMap. All rights reserved.