AndroidRecyclerView加载两种布局的方法

当RecyclerView有下拉刷新时,有时候设计图上,体现出来的列表有头部布局,这可以通过Adapter实现加载多套布局就可以,这里以加载两种布局为例说明。

创新互联主营龙安网站建设的网络公司,主营网站建设方案,成都app软件开发,龙安h5微信小程序搭建,龙安网站营销推广欢迎龙安等地区企业咨询

先看看Adapter的代码:

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.alvin.R;

import java.util.ArrayList;
import java.util.List;

public class MainListAdapter extends RecyclerView.Adapter{
 private List list;
 private ArrayList jdList;
 private Context context;

 public MainListAdapter(List list,ArrayList jdList, Context context) {
  this.list = list;
  this.jdList = jdList;
  this.context = context;
 }
 @Override
 public int getItemViewType(int position) {
  return list.get(position).getShowType();
 }
 @Override
 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  if(viewType==1){
   View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_header_main_list,parent,false);
   return new HeaderHolder(view);
  }else{
   View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_main,parent,false);
   return new ViewHolderItem(view);
  }
 }

 @Override
 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

  if(holder instanceof HeaderHolder){
   final HeaderHolder headerHolder = (HeaderHolder) holder;
   //TODO 实现相关逻辑
  }else if(holder instanceof ViewHolderItem){

  }
 }

 @Override
 public int getItemCount() {
  return list.size();
 }

 private class HeaderHolder extends RecyclerView.ViewHolder{

  HeaderHolder(View itemView) {
   super(itemView);
  }
 }

 private class ViewHolderItem extends RecyclerView.ViewHolder{

  ViewHolderItem(View itemView) {
   super(itemView);
  }
 }


}

getItemViewType()这个返回的是列表当前布局类型,在Adapter加载布局时,对齐进行判断,也就是onBindViewHolder()方法中进行相应的判断逻辑实现。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


网页名称:AndroidRecyclerView加载两种布局的方法
本文路径:http://hbruida.cn/article/pihhdi.html