Android RecycleView自定义布局的使用

自定义布局的RecycleView需要自己实现Adapter,ViewHolder和布局;

自定义Adapter继承RecycleView.Adapter,重写getItemCount(),onBindViewHolder()和onCreateViewHolder();

自定义ViewHolder继承于RecycleView.ViewHolder;

getItemCount()返回RecycleView中Item的个数,onBindViewHolder()主要实现数据和布局的绑定,onCreateViewHolder()加载布局;

效果:

Android RecycleView自定义布局的使用

适配器代码:

1 package com.cloud.recycleviewdemo; 2 3 import android.support.annotation.NonNull; 4 import android.support.v7.widget.RecyclerView; 5 import android.view.LayoutInflater; 6 import android.view.View; 7 import android.view.ViewGroup; 8 import android.widget.ImageView; 9 import android.widget.TextView; 10 11 import java.util.List; 12 13 class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ItemHolder> { 14 15 private List<Item> mItems; 16 17 RecycleViewAdapter(List<Item> items) { 18 mItems = items; 19 } 20 21 @Override 22 public int getItemCount() { 23 return mItems.size(); 24 } 25 26 @Override 27 public void onBindViewHolder(@NonNull ItemHolder holder, int position) { 28 //设置Item图片 29 holder.image.setImageResource(mItems.get(position).getImageResId()); 30 //设置Item文字 31 holder.title.setText(mItems.get(position).getTitle()); 32 } 33 34 @NonNull 35 @Override 36 public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 37 return new ItemHolder(LayoutInflater 38 .from(parent.getContext()).inflate(R.layout.item, parent, false)); 39 } 40 41 class ItemHolder extends RecyclerView.ViewHolder { 42 43 ImageView image; 44 TextView title; 45 46 ItemHolder(View item) { 47 super(item); 48 image = item.findViewById(R.id.image_view); 49 title = item.findViewById(R.id.text_title); 50 } 51 } 52 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgswj.html