简体   繁体   中英

CustomView inside RecyclerView

I create custom view on Android. I need to use it as items to the listview.

My custom view:

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

}

Adapter:

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

}

the problem is that the contents of the custom view was repeated. to test I write in the log a random number generated in custom view class. When scrolling through the list that number repeated, even if i only scroll down. What I need to do to make each element do not repeat the contents?

From the first look of it it seems like you're creating one ViewHolder (ChapterHolder) but you're binding another (RecyclerView.ViewHolder). In your adapter declaration it should be:

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ChapterHolder>

and then your onBindViewHolder will actually bind the right holder... and will look like this:

    public void onBindViewHolder(ChapterHolder holder, int position) {
        holder.setVerse(chapter.get(position), position);
        Log.d(Constants.LOG_TAG, getClass().getSimpleName() + ": random " + 
        holder.getRandom());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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