如何在片段中设置onItemclick

时间:2016-04-27 03:43:01

标签: android android-fragments onitemclicklistener

我试图在点击我的片段gridview中的图像时调用swipeview但是我无法正确显示它。之前我已经将我的gridview与mainactivity中的滑动视图相关联,但是这里我收到错误

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_one, container, false);
    GridView gridView=(GridView)view.findViewById(R.id.gridView);
    gridView.setAdapter(new MyAdapter(view.getContext()));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getBaseContext(),"Pic"+(position)+"Selected",Toast.LENGTH_SHORT).show();
            Intent intent= new Intent(view.getContext(),Main2Activity.class);
            intent.putExtra("pic",position);
            startActivity(intent);
        }
    });
    return view;
}

我在getbaseContext中遇到错误,我在设置MyAdapter(view.getContext()时可能出错,所以plz帮助解决错误

2 个答案:

答案 0 :(得分:2)

尝试使用getActivity()代替view.getcontext(),对于滑动视图,我认为您可以通过添加从左到右的动画来添加该功能。实际上我不明白在点击图像时调用swipeview是什么意思

答案 1 :(得分:0)

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_one, container, false);
    GridView gridView=(GridView)view.findViewById(R.id.gridView);
    gridView.setAdapter(new MyAdapter(view.getContext()));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getContext(),"Pic"+(position)+"Selected",Toast.LENGTH_SHORT).show();
            Intent intent= new Intent(getContext(),Main2Activity.class);
            intent.putExtra("pic",position);
            startActivity(intent);

        }
    });
    return view;
}