如何保持RecyclerView的按钮被分别单击-Android
作者:互联网
我有一个用CardViews填充的RecyclerView.在每个CardViews上都有一个按钮,可对该帖子进行投票.
这是未按下按钮时的外观,
这是按下按钮时的外观,
我的代码可以实现这一目标,但是由于它是RecyclerView,所以存在一个问题.当我向下滚动帖子时,RecyclerView会回收之前已投票的帖子.因此,即使用户从未投票过,帖子也会显示它已被投票.
如何保持每个CardView的按钮被分别按下?
这是我的适配器
public class DiscoverRecyclerAdapter
extends RecyclerView.Adapter<DiscoverRecyclerAdapter.ViewHolder> {
private String[] mDataset;
Typeface customFont;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public TextView mVoterCounter;
public ImageButton mVoterButton;
public ViewHolder(android.support.v7.widget.CardView v) {
super(v);
mTitle = (TextView) v.findViewById(R.id.title);
mVoterCounter = (TextView) v.findViewById(R.id.voter_counter);
//Initialize voter button
mVoterButton = (ImageButton)v.findViewById(R.id.voter);
mVoterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mVoterButton.setImageResource(R.drawable.ic_voter_pressed);
}
});
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public DiscoverRecyclerAdapter(String[] myDataset, Typeface passedFont) {
mDataset = myDataset;
customFont = passedFont;
}
// Create new views (invoked by the layout manager)
@Override
public DiscoverRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_discover, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder((android.support.v7.widget.CardView)v);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTitle.setText(mDataset[position]);
holder.mTitle.setTypeface(customFont);
holder.mVoterCounter.setTypeface(customFont);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
}
解决方法:
与mDataset一起,您还需要一个布尔数组,例如mIsSelected
现在,它的大小将等于数组mDataSet的大小,或者根据需要创建类.
然后在onBindViewHolder中执行
if(mIsSelected[position]
mVoterButton.setImageResource(R.drawable.ic_voter_pressed);
else
mVoterButton.setImageResource(R.drawable.ic_voter_unpressed);
并在onBindViewHolder内部移动按钮onclick,如下所示
holder.mVoterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mVoterButton.setImageResource(R.drawable.ic_voter_pressed);
mIsSelected[position] = true;
}
});
标签:android-recyclerview,android-button,android 来源: https://codeday.me/bug/20191028/1951854.html