我在Android上创建自定义视图。我需要将它作为列表视图中的项目使用。
我的自定义视图:
public class CustomView extends View{
int random;
//4 constructors;
public int getRandom() {
return random;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(w, h);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(b, 0,0,new Paint());
drawLetters(new Canvas(b));
}
private void init(){
drawingUtil = DrawingUtil.getInstance(getContext());
random = new Random().nextInt();
}
}
适配器:
public class ListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<String> chapter = new ArrayList<>();
Context context;
LayoutInflater inflater;
public ListAdapter(List<String> chapter, Context context) {
this.chapter = chapter;
this.context = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.item, null);
return new ChapterHolder(v);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ChapterHolder) holder).setVerse(chapter.get(position), position);
Log.d(Constants.LOG_TAG, getClass().getSimpleName() + ": random " + ((ChapterHolder) holder).getRandom());
}
@Override
public int getItemCount() {
return chapter.size();
}
}
问题是重复了自定义视图的内容。测试我在日志中写入自定义视图类中生成的随机数。滚动列表中重复的数字,即使我只向下滚动。我需要做些什么来使每个元素不重复内容?
答案 0 :(得分:0)
从它的第一眼看起来,你似乎正在创建一个ViewHolder(ChapterHolder),但你正在绑定另一个(RecyclerView.ViewHolder)。在您的适配器声明中,它应该是:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ChapterHolder>
然后你的onBindViewHolder将实际绑定权利持有者......并且看起来像这样:
public void onBindViewHolder(ChapterHolder holder, int position) {
holder.setVerse(chapter.get(position), position);
Log.d(Constants.LOG_TAG, getClass().getSimpleName() + ": random " +
holder.getRandom());
}