What is the right way of Android View Binding in the RecyclerView adapter class?

前端 未结 5 1439
[愿得一人]
[愿得一人] 2021-02-14 07:08

Here is the code I used in my RecycleView adapter class. I don\'t know this is the right way or not to use View Binding. If you have a better solution answer me. Th

5条回答
  •  有刺的猬
    2021-02-14 07:48

    What you need to do is pass the generated binding class object to the holder class constructor. In your example, You have common_circle_image XML file for RecyclerView item and the generated class is CommonCircleImageBinding so like this you use the onCreateViewHolder to pass the generated binding class to the ViewHolder class

    @NonNull
    @Override
    public CategoryAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        CommonCircleImageBinding itemBinding = CommonCircleImageBinding .inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new MyViewHolder(itemBinding);
    }
    

    and use the holder class like this so you can use these fields in onBindViewHolder

    static class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView txt;
        private ImageView img; 
    
        MyViewHolder(CommonCircleImageBinding itemBinding) {
            super(itemBinding.getRoot());
            img = itemBinding.img ;
            txt = itemBinding.txt ;
        }
    }
    

提交回复
热议问题