當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()中進行對應的邏輯方法中進行對應的邏輯方法實現。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。
更多Android RecyclerView載入兩種版面的方法相關文章請關注PHP中文網!