我需要使用Android Recycler View来解决如何执行以下操作的问题。
我有多个图像,我只需要选择一个图像,就像单选按钮的工作方式一样。现在我可以选择我拥有的所有图像,但我需要限制当前的工作行为,就像单选按钮(例如)如果选择了一个,我不应该选择其他图像。
我尝试使用以下代码,但对我来说没有运气。任何人都可以纠正错误,并根据我的需要使代码可行。
public class StarCountAdapter extends RecyclerView.Adapter<StarCountAdapter.StarCountHolder> {
Context context;
LayoutInflater inflater;
List<StarCount> starCounts = new ArrayList<>();
public StarCountAdapter(Context context, List<StarCount> starCounts) {
this.context = context;
this.inflater = LayoutInflater.from(context);
this.starCounts = starCounts;
}
@Override
public StarCountHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.star_count_row,parent,false);
return new StarCountHolder(view);
}
@Override
public void onBindViewHolder(StarCountHolder holder, int position) {
StarCount model = starCounts.get(position);
Picasso.with(context)
.load("http://"+model.getImagePath())
.into(holder.starImage);
holder.actorName.setText(model.getName());
holder.counts.setText(""+model.getCount());
}
@Override
public int getItemCount() {
return starCounts.size();
}
public class StarCountHolder extends RecyclerView.ViewHolder {
ImageView starImage;
TextView actorName,counts;
StarCount modelCount;
public StarCountHolder(View itemView) {
super(itemView);
starImage = (ImageView) itemView.findViewById(R.id.starCountIv);
actorName = (TextView) itemView.findViewById(R.id.acterName);
counts = (TextView) itemView.findViewById(R.id.counts);
}
}
}
需要帮助解决这个问题,因为我被打了一天以上。分享想法以纠正我在代码中的错误并纠正我的错误。
答案 0 :(得分:2)
public int selectedPosition = -1
public class StarCountHolder extends RecyclerView.ViewHolder {
ImageView starImage;
TextView actorName,counts;
StarCount modelCount;
public StarCountHolder(View itemView) {
super(itemView);
starImage = (ImageView) itemView.findViewById(R.id.starCountIv);
actorName = (TextView) itemView.findViewById(R.id.acterName);
counts = (TextView) itemView.findViewById(R.id.counts);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedPosition = getLayoutPosition());
notifyDatasetChanged();
}
});
}
}
现在您已完成所选项目位置,在您的活页夹中进行更改
@Override
public void onBindViewHolder(StarCountHolder holder, int position) {
StarCount model = starCounts.get(position);
Picasso.with(context)
.load("http://"+model.getImagePath())
.into(holder.starImage);
holder.actorName.setText(model.getName());
holder.counts.setText(""+model.getCount());
if(selectedPosition == position){
// do whatever you want to do to make it selected.
}
}
现在要在您的活动中获取所选项目,您可以执行以下操作...
内部活动
StartCount startC = starCounts.get(adapter.selectedPosition);
希望有所帮助