我想获取 ListView 的 SelectedItem 索引。我通过点击项目来选择项目。 OnItemClick 事件工作正常,但 getSelectedItemPosition() 返回 -1。
我做错了什么?
xml:
<ListView
android:id="@+id/lvAddEdtList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:listSelector="?android:attr/listChoiceIndicatorSingle" />
在 Activity 中:
lvAddEdtDel.setAdapter(namesList);
lvAddEdtDel.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lvAddEdtDel.setSelection(position);
view.setSelected(true);
}
});
public void onClick(View v) {
if(lvAddEdtDel.getSelectedItemPosition() < 0 )
{
Toast.makeText(getApplicationContext(), getString(R.string.ItemNotSelected),Toast.LENGTH_LONG).show();
}
});
抱歉我的英语不好
最佳答案
我自己解决了这个问题。 适配器的布局已选择:android.R.layout.simple_list_item_1;
在我的例子中,有必要选择:android.R.layout.simple_list_item_single_choice;
在触摸模式下必须使用 getCheckedItemPosition
关于android - ListView item "don' t want be a selected"getSelectedItemPosition return -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187603/