为Spinner项设置onClickListener?

37

我有一个从数据库中获取数据的旋转器(spinner):

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);

我想在选择最后一个项目(添加新类别...)时调用AlertDialog
在我添加新类别之后,我希望"项目(添加新类别...)"再次成为最后一个。
我该如何做到这一点?

2个回答

103

不应该在Spinner上调用OnItemClickListener,因为它不支持项目点击事件。调用此方法将引发异常。请查看这里

相反,你可以使用OnItemSelectedListener来实现相应的功能。

编辑:

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) 
    {

    }           
});

如果你想把"添加新类别"放在列表的末尾,我建议你使用自定义适配器。在适配器中添加完所有项目后,你可以将该常量("添加新类别")添加到数组的末尾,以便它始终出现在最后。


1
我知道这个。但是在 OnItemSelectedListener 中,我如何处理只选择一个项目? - Volodymyr
1
当您选择任何项目时,您将获得所选项目。将所选项目与您预定义的常量项目进行比较。如果所选项目是该预定义项目,则执行您的任务。 - Braj
它不起作用。我认为是因为这个 parent.getItemAtPosition(position).toString(); 返回位置并将其转换为字符串。 - Volodymyr
它将返回该位置的特定对象并将其转换为字符串。它不会返回位置。要获取位置或项目ID,需要使用parent.getItemIdAtPosition(position)方法。 - Braj
您忘记了 onItemSelected(...) 的 "}"。 - Igor Beaufils
请注意重要信息:onItemSelected将会在初始化时和用户手动选择时触发两次。这意味着,如果你的“// do your stuff”在代码中进行了某种初始化操作,你不需要在其他地方声明它——spinner会自动调用它,而无需用户明确选择。 - Morphing Coffee

7

钩子到Spinner的OnItemClickListener。然后检查所选项目是否为“添加新类别”。

如果是,显示对话框以添加新项目。

在添加新项目时,

  1. 删除最后一个项目“添加新类别”。
  2. 添加输入的新类别。
  3. 然后再次添加项目“添加新类别”。

这将使“添加新类别”项目成为最后一个项目。

代码示例:

布局 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>

布局 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>

活动类:

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);
}

}

一个OnItemClickListener无法连接到Spinner。 - SoroushA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接