复习ReclerView多布局

使用ReclerView布局实现多布局

初始化Recycler

复习ReclerView多布局_第1张图片

初始化数据源

复习ReclerView多布局_第2张图片

自定义 ViewHolder类

复习ReclerView多布局_第3张图片

自定义适配器

public class MyAdapter extends RecyclerView.Adapter {
    private final int Header=1;
    private final int Body=2;
    private final int Foot=3;

    ArrayListlist=new ArrayList<>();

//自定义添加数据方法
    public void initList(ArrayListarrayList){
        list.clear();
        list.addAll(arrayList);
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public BaseHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        if(i==Header){
          View view=View.inflate(viewGroup.getContext(),R.layout.header,null);
            return new BaseHolder(viewHeader);
        }else if(i==Foot){
            View view=View.inflate(viewGroup.getContext(),R.layout.foot,null);
            return new BaseHolder(view);
        } else{
            View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.body,null,false);
            return new BaseHolder(view);

        }

    }
    @Override
    public void onBindViewHolder(@NonNull BaseHolder baseHolder, int i) {

        if(i==0&&viewHeader!=null){
            return;
        }else if(i==getItemCount()-1){
           return;
        }else{
            TextView textView =(TextView) baseHolder.getView(R.id.t_body);
            textView.setText(list.get(i-1));
        }
    }


    @Override
    public int getItemViewType(int position) {
        if(position==0){
            return Header;
        }else if(position==getItemCount()-1){
            return Foot;
        }else{
            return Body;
        }

    }

    @Override
    public int getItemCount() {
        int count = list.size();
        if(viewHeader!=null){
            count+=2;
        }
        return count;
    }
}

效果:

复习ReclerView多布局_第4张图片

你可能感兴趣的:(ReclerView,ReclerView多布局)