片段onListItemClick

时间:2012-12-10 23:22:34

标签: android listview android-fragments onclick fragment

当我点击item时,我的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 个答案:

答案 0 :(得分: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 {

    /* ... */

}

答案 1 :(得分:3)

您忘了设置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);                 
    }
});

答案 2 :(得分: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
    }

}

答案 3 :(得分:0)

你的片段必须扩展ListFragment,如果你的布局有一个id = android:id / list

的列表视图,你的布局可以有更多的东西而不是列表