回收视图:定位并切换到活动

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (15)

控件中单击的项的位置是如何获得的。RecyclerView中的某个活动的意图。onClick方法?这是我的适配器:

public class SergejAdapter extends RecyclerView.Adapter<SergejAdapter.MyViewHolder>{

    private LayoutInflater inflater;
    List<Information> data= Collections.emptyList();

    public SergejAdapter(Context context, List<Information> data){
      inflater = LayoutInflater.from(context);
        this.data=data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.navigation_drawer_custom_row,parent,false);
        MyViewHolder holder= new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView){
            super(itemView);
            title= (TextView) itemView.findViewById(R.id.listText);
            icon = (ImageView) itemView.findViewById(R.id.listIcon);
            icon.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent intent = new Intent(context, Ernaehrung.class);
            context.startActivity(intent);

        }
    }

我只是有一个onClick当其中一个图片被点击,但每个图像都有相同的意图。

提问于
用户回答回答于

可以从ViewHolder获取位置,方法是getAdapterPosition()。如下代码所示:

public class SergejAdapter extends RecyclerView.Adapter<SergejAdapter.MyViewHolder>{

    ...

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{


        @Override
        public void onClick(View v) {
            // here you use position
            int position = getAdapterPosition();
            ...

        }
    }
}
用户回答回答于

或者你只需加上:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder > {

...
    class MyViewHolder extends RecyclerView.ViewHolder {

        public MyViewHolder (View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                }
            });
        }


    }

扫码关注云+社区