列出项目单击侦听器上的片段

时间:2014-05-29 09:49:46

标签: android android-fragments

我正在尝试使用OnItemClickListener在Android的ListFragment上做一个列表,但我不能,我点击n列表项,没有任何反应。我是碎片的新手。这是我的代码。谢谢!

public class MyFragment extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v= inflater.inflate(R.layout.hello, container, false);



     ListView lv =(ListView) v.findViewById(android.R.id.list);


        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                // getting values from selected ListItem
                String titulo = ((TextView) v.findViewById(R.id.title))
                        .getText().toString();
                String contenido = ((TextView) v.findViewById(R.id.content))
                .getText().toString();
                String fecha = ((TextView) v.findViewById(R.id.date))
                        .getText().toString();

                // Starting new detail
                Intent in = new Intent(getActivity().getApplicationContext(),
                        NoticiasFragment.class);
                in.putExtra("title", titulo);
                in.putExtra("content", contenido);
                in.putExtra("date", fecha);
                startActivity(in);


            }


    return v;
}

2 个答案:

答案 0 :(得分:12)

ListFragment有一个内置的onListItemClick函数可以覆盖。

你应该这样做:

public class MyFragment extends ListFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v= inflater.inflate(R.layout.hello, container, false);
        return v;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        //Do your stuff..
    }

}

答案 1 :(得分:0)

移动代码:

        lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            // getting values from selected ListItem
            String titulo = ((TextView) v.findViewById(R.id.title))
                    .getText().toString();
            String contenido = ((TextView) v.findViewById(R.id.content))
            .getText().toString();
            String fecha = ((TextView) v.findViewById(R.id.date))
                    .getText().toString();

            // Starting new detail
            Intent in = new Intent(getActivity().getApplicationContext(),
                    NoticiasFragment.class);
            in.putExtra("title", titulo);
            in.putExtra("content", contenido);
            in.putExtra("date", fecha);
            startActivity(in);


        }

to Fragment的onActivityCreated()方法。