繁体   English   中英

RecyclerView 中的 CustomView

[英]CustomView inside RecyclerView

我在 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();
    }

}

问题是自定义视图的内容重复了。 为了测试,我在日志中写入了一个在自定义视图类中生成的随机数。 滚动列表时,该数字会重复,即使我只向下滚动。 我需要做什么才能使每个元素不重复内容?

乍一看,您似乎正在创建一个 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());
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM