当前位置:主页 > 移动开发 > Android代码 >

Android RecyclerView加载两种布局的方法

时间:2021-01-21 10:50:15 | 栏目:Android代码 | 点击:

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

先看看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<RecyclerView.ViewHolder>{
 private List<Data> list;
 private ArrayList<ItemEntity> jdList;
 private Context context;

 public MainListAdapter(List<Data> list,ArrayList<ItemEntity> 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()方法中进行相应的判断逻辑实现。

您可能感兴趣的文章:

相关文章