gpt4 book ai didi

android - RecyclerView : get position and switch to activity

转载 作者:IT老高 更新时间:2023-10-28 23:17:07 28 4
gpt4 key购买 nike

如何获得在 RecyclerView 行中被点击的项目的位置,而不是在 onClick 方法中对 Activity 做出 Intent ?这是我的适配器:

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 当点击其中一张图片时,但每张图片都有相同的 Intent 。

最佳答案

您可以使用 getAdapterPosition() 方法从 ViewHolder 获取位置。就像下面的代码:

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();
...

}
}
}

关于android - RecyclerView : get position and switch to activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886737/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com