我需要多選/單選幫助。找到我正在尋找的here,因爲它的簡單性。 我使用的是GridLayoutManager
我在適配器中有90多個項目,CardView
使用TextView
和ImageView
,同時使用the post中描述的過程。在Android中實現多選選項RecyclerView
當我向下滾動時選擇一個或多個項目時,其他項目「似乎」被選中,因爲後臺複製,但未選中。 試圖把setOnClickListener
,在onBindViewHolder
,也在MyViewHolder類,並在他們兩個我得到相同的行爲。當向下滾動其他項目似乎被選中。 在適配器中使用了notifyItemChanged(position)
和notifyDataSetChanged()
,但背景完全沒有改變,但setSelected
正常工作。 另外我在RecyclerView設置中使用了setHasFixedSize(true)
。
在onBindViewHolder
@Override
public void onBindViewHolder(MyViewHolder myViewHolder, final int position) {
PatternImages currentPattern = patternImages.get(position);
myViewHolder.setData(currentPattern, position);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setSelected(!v.isSelected());
if (v.isSelected()) {
v.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryHighLight));
} else {
v.setBackgroundColor(Color.WHITE);
}
notifyItemChanged(position);
}
});
}
模型
public class PatternImages {
private int imageId, imageName;
private boolean isSelected;
public PatternImages(int imageId, int imageName, boolean isSelected) {
this.imageId = imageId;
this.imageName = imageName;
this.isSelected = isSelected;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public int getImageName() {
return imageName;
}
public void setImageName(int imageName) {
this.imageName = imageName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
RecyclerView設置
private void setUpPatternsRecyclerView() {
RecyclerView recyclerPatternsView = (RecyclerView) findViewById(R.id.pattern_image_recycler_view);
PatternImageAdapter adapter = new PatternImageAdapter(this, patternImages);
recyclerPatternsView.setAdapter(adapter);
ColumnQty columnQty = new ColumnQty(this, R.layout.item_image_pattern_cardview);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), columnQty.calculateNoOfColumns());
recyclerPatternsView.setHasFixedSize(true);
recyclerPatternsView.setLayoutManager(gridLayoutManager);
recyclerPatternsView.setItemAnimator(new DefaultItemAnimator());
recyclerPatternsView.addItemDecoration(new GridSpacing(columnQty.calculateSpacing()));
}
SetData方法
public void setData(PatternImages currentPattern, int position) {
this.position = position;
patternName.setText(context.getString(currentPattern.getImageName()));
patternName.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ElMessiri-SemiBold.ttf"));
patternImage.setBackgroundResource(currentPattern.getImageId());
if (position == 0 || position == 1) {
animationDrawable = (AnimationDrawable) patternImage.getBackground();
animationDrawable.start();
}
}
把代碼第一 –
@阿維納什·羅伊,完成 – Racu