setOnItemClickListener for ListView in a fragment

混江龙づ霸主 提交于 2019-12-04 13:11:30

The place to add your ListView.SetOnItemClickListener is in your fragment creation code, after you inlfate the layouts. Use findViewById to find your ListView, and add your setOnItemClick listener.

class ResourcesFragment extends Fragment{

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

        View view = inflater.inflate(R.layout.resources_fragment, container, false);
        ListView lv = (ListView) view.findViewById(R.id.mylistviewid);

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub

                        String category = categories[position];
                        Class activityClass = lookupActivityClass_byName(category);
                        //You could lookup by position, but "name" is more general

                        Intent intent = new Intent(getActivity(), activityClass);
                        startActivity(intent);


            }
        });

        return view;

    }

When you use Fragment, you can find views inside onCreateView(). In simpler term, it's same as of onCreate() of Activity.

So in this case, find ListView inside onCreateView() and assign onItemClickListener there only.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!