我有一个用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; } });
总结 以上是内存溢出为你收集整理的如何保持RecyclerView的按钮被分别单击-Android全部内容,希望文章能够帮你解决如何保持RecyclerView的按钮被分别单击-Android所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)