Android ListView-获取所选项目 [英] Android ListView - get the selected item
问题描述
我已经使用自定义数组适配器实现了列表视图.现在,我要获取列表视图的选定项.我知道有一些使用onclick侦听器的解决方案.但是,我想使用ListView(AdapterView)类的getSelectedItem()方法.该方法始终返回null.其他getSelected *方法也不起作用.
I have implemented a list view using a custom array adapter. Now I want to get the selected item of the list view. I know that there are solutions using onclick listeners. However I would like to use the getSelectedItem() method of the ListView (AdapterView) class. The method always returns null. The other getSelected* methods also do not work.
// onCreate
mList = (ListView) findViewById(R.id.listView);
// set in Broadcast Receiver (inner class)
mList.setAdapter(new ListAdapter(getApplicationContext(),
R.layout.list_view_item, R.id.textView,
itemList));
// onButtonClick
Log.i(TAG, "Selected: " + mList.getSelectedItem());
OnButtonClick是一个单独按钮的回调.如果单击它,则所选项目应在logcat中打印,但每次返回null.谁能帮我吗?
OnButtonClick is a callback of a seperate button. If I click on it the selected item should be printed in logcat but it returns everytime null. Can anyone help me?
XML:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@android:color/background_light"
android:drawSelectorOnTop="false"
android:listSelector="@android:color/holo_blue_light" >
</ListView>
<Button
android:id="@+id/buttonContinue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/listView"
android:layout_centerHorizontal="true"
android:onClick="onButtonClickContinue"
android:text="Continue" />
</RelativeLayout>
如果我选择一个项目,颜色就会改变.
If I select an item the color changes.
推荐答案
我发现从不/很少在触摸设备上调用OnItemSelected方法. 如果您使用仿真器交叉导航,并且在具有混合或非触摸控制的特殊设备上触发,则它将触发.仅当您滚动列表时才调用它,而单击时不会调用.
I figured out that the OnItemSelected method is never/rarely called on touch devices. It fires up if you use the emulator cross-navigation and on special devices with hybrid or non-touch control. It is only called if you scroll through the list but not if you click on it.
这就是为什么您应该在具有触摸控制功能的普通平板电脑/智能手机上使用OnItemClickListener.
Thats why you should use the OnItemClickListener on a general tablet/smartphone with touch control.
这篇关于Android ListView-获取所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!