首页 > 系统 > Android > 正文

Android RecyclerView加载两种布局的方法

2019-12-12 03:46:58
字体:
来源:转载
供稿:网友

当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()方法中进行相应的判断逻辑实现。

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表