无法在Adapter类中解析ListView

时间:2016-05-17 20:26:40

标签: android

我想在我的适配器类中单击列表视图的listitem时实现一个对话框。如何从其他班级访问我的ListView

public void onClick(View v) {
    AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
    adb.setTitle("LVSelectedItemExample");
    adb.setMessage("Selected Item is = " + listView.getItemAtPosition(position));
    adb.setPositiveButton("Ok", null);
    adb.show();
}

3 个答案:

答案 0 :(得分:1)

为什么要在Adapter类中创建。在您的活动或片段中使用listview.setOnItemClickListener(this)

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    });
你的onCreate()方法中的

答案 1 :(得分:0)

试试这个 -

public void onClick(View v) {
    AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
    adb.setTitle("LVSelectedItemExample");
    adb.setMessage("Selected Item is = " + getItem(position));
    adb.setPositiveButton("Ok", null);
    adb.show();
}

或在包含onItemClick()

的活动/片段中实施ListView侦听器

答案 2 :(得分:0)

您的示例代码使用onClick,您应该onItemClick

您的代码如下所示:

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            MyAdapter adapter = (MyAdapter) parent.getAdapter; // use your actual adapter class name here

            AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
            adb.setTitle("LVSelectedItemExample");
            adb.setMessage("Selected Item is = " + adapter.getItem(position));
            adb.setPositiveButton("Ok", null);
            adb.show();
        }
    });

确保在适配器中正确实现getItem