我已经使用自定义数组适配器实现了列表视图。现在,我要获取列表视图的选定项。我知道有一些使用onclick侦听器的解决方案。但是,我想使用ListView(AdapterView)类的getSelectedItem()方法。该方法始终返回null。其他getSelected *方法也不起作用。

// 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。谁能帮我?

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>


如果我选择一个项目,颜色会改变。

最佳答案

我检查了getSelectedItem源代码

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


也许您应该检查getItem中的ListAdapter方法

08-17 17:28
查看更多