片段和设置OnItemClickListener

时间:2015-09-15 11:21:29

标签: android android-fragments android-arrayadapter onitemclicklistener

我有一个Fragments项目。在主片段上我有一个列表与项目(pic相关),这是通过使用自定义适配器生成的,我想我需要使用OnItemClickListener来点击进入另一个活动的项目。下面是我的HomeFragment类的一个片段,这里是我想创建一个OnItemClickListener的地方,它可能吗?我怎样才能做到这一点?

public class HomeFragment extends Fragment implements OnClickListener {
    public HomeFragment() {
        // Required empty public constructor
    }
    View rootView;

    @Override
    public void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }


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

        rootView = inflater.inflate(R.layout.fragment_home, container, false);


        RowBean RowBean_data[] = new RowBean[]{
                new RowBean(R.drawable.kamil, "Kamil "),
                new RowBean(R.drawable.bartlomiej, "Bartlomiej "),
                new RowBean(R.drawable.krzysztof, "Krzysztof ")
        };


        CustomAdapter adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.list_style, RowBean_data);
        ListView lista = (ListView) rootView.findViewById(R.id.lista);
        lista.setAdapter(adapter);


        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {        super.onAttach(activity);    }

    @Override    public void onDetach() {        super.onDetach();    }

    @Override    public void onClick(View v) {      Toast.makeText(getActivity(), "Works!", Toast.LENGTH_SHORT).show();    }

}

screen

2 个答案:

答案 0 :(得分:2)

return rootView;方法

中的onCreateView语句之前添加以下侦听器
 lista.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                 //do stuff
                 Intent intent=new Intent(CurrentActivity.this,AnotherActivty.class);
                 startActivity(intent);
            }
        });

答案 1 :(得分:1)

是。你必须使用onItemClickListener() 您可以通过以下方式使用它:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
            // You can launch activity here in your case.
    }
});