3

当我单击项目时,我的 onListItemClick 永远不会被调用,该类是扩展片段而不是 listfragment,因为我在这个片段中有其他视图项目不是列表,那么如何在类扩展片段中实现 onlistitemclick?

班级

public class MainFiles extends Fragment 
{
    ArrayList<String> items;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View view = inflater.inflate(R.layout.files, container, false);

        Button button_up = (Button) view.findViewById(R.id.button_up);
        items = new ArrayList<String>();

        MyAdapter adapter = new MyAdapter(getActivity(), R.layout.row, items);
        ListView myList = (ListView) view.findViewById(R.id.list);
        myList.setAdapter(adapter);

        return view;
    }

    public void onListItemClick(ListView l, View v, int position, long id) 
    {

    }
}
4

4 回答 4

4

显式添加OnItemClickListener到您的ListView

myList.setOnItemClickListener(this);

您还必须确保您Fragment实现了以下OnItemClickListener类型:

public class MainFiles extends Fragment implements OnItemClickListener

另一种方法是创建一个专用的子类OnItemClickListener来传递给ListView

myList.setOnItemClickListener(new MyOnItemClickListener());

/* ... */

private class MyOnItemClickListener implements OnItemClickListener {

    /* ... */

}
于 2012-12-10T23:33:57.357 回答
2

您忘记设置 setOnItemClickListener

添加后myList.setAdapter(adapter);

myList.setOnItemClickListener(new OnItemClickListener(){
    public void onItemClick(AdapterView<?> parent, View view, int position,long id){
        new File(items.get(position));
        fileList(path.get(position));
        showPath(current_path);                 
    }
});
于 2012-12-10T23:35:45.843 回答
2

我在这样的片段中实现了监听器

public class DetailsFragment extends Fragment implements OnItemClickListener {

    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_details, container, false);

        // list view
        listView = (ListView) root.findViewById(R.id.listView);
        listView.setListAdapter(new DetailsAdapter(getActivity(), list));
        listView.setOnItemClickListener(this);

        return root;
    }

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

}
于 2012-12-10T23:58:44.470 回答
0

您的片段必须扩展 ListFragment,如果您的布局有一个 id=android:id/list 的列表视图,您的布局中可以有更多的东西而不是列表

于 2014-02-06T17:40:42.833 回答