我有一个RecyclerView,其中填充了CardViews。每个CardView上都有一个按钮,用于点赞帖子。
以下是未按下时按钮的外观:
以下是按下时按钮的外观:
我的代码可以实现这一点,但是由于它是一个RecyclerView,我遇到了一个问题。当我向下滚动帖子时,RecyclerView会回收之前已经点赞的帖子。因此,即使用户从未点赞过某个帖子,该帖子也会显示为已被点赞。
我该如何保持每个CardView中的按钮分别处于按下状态?
以下是我的Adapter:
以下是未按下时按钮的外观:
![up vote - not pressed](https://istack.dev59.com/5Bqs8.webp)
![up vote - pressed](https://istack.dev59.com/FaTZt.webp)
我该如何保持每个CardView中的按钮分别处于按下状态?
以下是我的Adapter:
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;
}
}