Android ListView - get the selected item

旧巷老猫 提交于 2019-12-24 12:38:27

问题


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 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.


回答1:


I check the getSelectedItem source code

public Object getSelectedItem() {
    T adapter = getAdapter();
    int selection = getSelectedItemPosition();
    if (adapter != null && adapter.getCount() > 0 && selection >= 0) {
        return adapter.getItem(selection);
    } else {
        return null;
    }
}

maybe you should check your the getItem method in the ListAdapter




回答2:


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.

Thats why you should use the OnItemClickListener on a general tablet/smartphone with touch control.




回答3:


Implement you class

public class xyz extends Activity implements OnItemSelectedListener

then give onitemclicklistener of that activity

mList.setOnItemSelectedListener(this);

And now implement the onItemselected method

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // u will get the position and selected item here
}


来源:https://stackoverflow.com/questions/26399757/android-listview-get-the-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!