1. 程式人生 > >[Android]自由新增Head和Foot對RecyclerView的Adapter

[Android]自由新增Head和Foot對RecyclerView的Adapter

該Adapter能達到給RecyclerView自由新增Head和View的目的,且新增的Head和Foot不受LayouManager干擾,程式碼如下:

public class BaseHeaderAndFooterAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int BASE_ITEM_TYPE_HEADER = 100000;
    private static final int BASE_ITEM_TYPE_FOOTER = 200000
; private SparseArrayCompat<View> mHeaderViews = new SparseArrayCompat<>(); private SparseArrayCompat<View> mFootViews = new SparseArrayCompat<>(); private RecyclerView.Adapter mInnerAdapter; public BaseHeaderAndFooterAdapter(RecyclerView.Adapter adapter) { mInnerAdapter = adapter; } private
boolean isHeaderViewPos(int position) { return position < getHeadersCount(); } private boolean isFooterViewPos(int position) { return position >= getHeadersCount() + getRealItemCount(); } public void addHeaderView(View view) { mHeaderViews.put(mHeaderViews.size() + BASE_ITEM_TYPE_HEADER, view); } public
void addFootView(View view) { mFootViews.put(mFootViews.size() + BASE_ITEM_TYPE_FOOTER, view); } public int getHeadersCount() { return mHeaderViews.size(); } public int getFootersCount() { return mFootViews.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (mHeaderViews.get(viewType) != null) { ViewHolder holder = ViewHolder.createViewHolder(parent.getContext(), mHeaderViews.get(viewType)); return holder; } else if (mFootViews.get(viewType) != null) { ViewHolder holder = ViewHolder.createViewHolder(parent.getContext(), mFootViews.get(viewType)); return holder; } return mInnerAdapter.onCreateViewHolder(parent, viewType); } @Override public int getItemViewType(int position) { if (isHeaderViewPos(position)) { return mHeaderViews.keyAt(position); } else if (isFooterViewPos(position)) { return mFootViews.keyAt(position - getHeadersCount() - getRealItemCount()); } return mInnerAdapter.getItemViewType(position - getHeadersCount()); } private int getRealItemCount() { return mInnerAdapter.getItemCount(); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (isHeaderViewPos(position)) { return; } if (isFooterViewPos(position)) { return; } mInnerAdapter.onBindViewHolder(holder, position - getHeadersCount()); } @Override public int getItemCount() { return getHeadersCount() + getFootersCount() + getRealItemCount(); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { WrapperUtils.onAttachedToRecyclerView(mInnerAdapter, recyclerView, new WrapperUtils.SpanSizeCallback() { @Override public int getSpanSize(GridLayoutManager layoutManager, GridLayoutManager.SpanSizeLookup oldLookup, int position) { int viewType = getItemViewType(position); if (mHeaderViews.get(viewType) != null) { return layoutManager.getSpanCount(); } else if (mFootViews.get(viewType) != null) { return layoutManager.getSpanCount(); } if (oldLookup != null) return oldLookup.getSpanSize(position); return 1; } }); } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { mInnerAdapter.onViewAttachedToWindow(holder); int position = holder.getLayoutPosition(); if (isHeaderViewPos(position) || isFooterViewPos(position)) { WrapperUtils.setFullSpan(holder); } } public static class ViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; private View mConvertView; private Context mContext; public ViewHolder(Context context, View itemView) { super(itemView); mContext = context; mConvertView = itemView; mViews = new SparseArray<View>(); } public static ViewHolder createViewHolder(Context context, View itemView) { ViewHolder holder = new ViewHolder(context, itemView); return holder; } public static ViewHolder createViewHolder(Context context, ViewGroup parent, int layoutId) { View itemView = LayoutInflater.from(context).inflate(layoutId, parent, false); ViewHolder holder = new ViewHolder(context, itemView); return holder; } /** * 通過viewId獲取控制元件 * * @param viewId * @return */ public <T extends View> T getView(int viewId) { View view = mViews.get(viewId); if (view == null) { view = mConvertView.findViewById(viewId); mViews.put(viewId, view); } return (T) view; } public View getConvertView() { return mConvertView; } /****以下為輔助方法*****/ /** * 設定TextView的值 * * @param viewId * @param text * @return */ public ViewHolder setText(int viewId, String text) { TextView tv = getView(viewId); tv.setText(text); return this; } public ViewHolder setImageResource(int viewId, int resId) { ImageView view = getView(viewId); view.setImageResource(resId); return this; } public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) { ImageView view = getView(viewId); view.setImageBitmap(bitmap); return this; } public ViewHolder setImageDrawable(int viewId, Drawable drawable) { ImageView view = getView(viewId); view.setImageDrawable(drawable); return this; } public ViewHolder setBackgroundColor(int viewId, int color) { View view = getView(viewId); view.setBackgroundColor(color); return this; } public ViewHolder setBackgroundRes(int viewId, int backgroundRes) { View view = getView(viewId); view.setBackgroundResource(backgroundRes); return this; } public ViewHolder setTextColor(int viewId, int textColor) { TextView view = getView(viewId); view.setTextColor(textColor); return this; } public ViewHolder setTextColorRes(int viewId, int textColorRes) { TextView view = getView(viewId); view.setTextColor(mContext.getResources().getColor(textColorRes)); return this; } @SuppressLint("NewApi") public ViewHolder setAlpha(int viewId, float value) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getView(viewId).setAlpha(value); } else { // Pre-honeycomb hack to set Alpha value AlphaAnimation alpha = new AlphaAnimation(value, value); alpha.setDuration(0); alpha.setFillAfter(true); getView(viewId).startAnimation(alpha); } return this; } public ViewHolder setVisible(int viewId, boolean visible) { View view = getView(viewId); view.setVisibility(visible ? View.VISIBLE : View.GONE); return this; } public ViewHolder linkify(int viewId) { TextView view = getView(viewId); Linkify.addLinks(view, Linkify.ALL); return this; } public ViewHolder setTypeface(Typeface typeface, int... viewIds) { for (int viewId : viewIds) { TextView view = getView(viewId); view.setTypeface(typeface); view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG); } return this; } public ViewHolder setProgress(int viewId, int progress) { ProgressBar view = getView(viewId); view.setProgress(progress); return this; } public ViewHolder setProgress(int viewId, int progress, int max) { ProgressBar view = getView(viewId); view.setMax(max); view.setProgress(progress); return this; } public ViewHolder setMax(int viewId, int max) { ProgressBar view = getView(viewId); view.setMax(max); return this; } public ViewHolder setRating(int viewId, float rating) { RatingBar view = getView(viewId); view.setRating(rating); return this; } public ViewHolder setRating(int viewId, float rating, int max) { RatingBar view = getView(viewId); view.setMax(max); view.setRating(rating); return this; } public ViewHolder setTag(int viewId, Object tag) { View view = getView(viewId); view.setTag(tag); return this; } public ViewHolder setTag(int viewId, int key, Object tag) { View view = getView(viewId); view.setTag(key, tag); return this; } public ViewHolder setChecked(int viewId, boolean checked) { Checkable view = (Checkable) getView(viewId); view.setChecked(checked); return this; } /** * 關於事件的 */ public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener) { View view = getView(viewId); view.setOnClickListener(listener); return this; } public ViewHolder setOnTouchListener(int viewId, View.OnTouchListener listener) { View view = getView(viewId); view.setOnTouchListener(listener); return this; } public ViewHolder setOnLongClickListener(int viewId, View.OnLongClickListener listener) { View view = getView(viewId); view.setOnLongClickListener(listener); return this; } } /** * Created by zhy on 16/6/28. */ public static class WrapperUtils { public interface SpanSizeCallback { int getSpanSize(GridLayoutManager layoutManager, GridLayoutManager.SpanSizeLookup oldLookup, int position); } public static void onAttachedToRecyclerView(RecyclerView.Adapter innerAdapter, RecyclerView recyclerView, final SpanSizeCallback callback) { innerAdapter.onAttachedToRecyclerView(recyclerView); RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager; final GridLayoutManager.SpanSizeLookup spanSizeLookup = gridLayoutManager.getSpanSizeLookup(); gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return callback.getSpanSize(gridLayoutManager, spanSizeLookup, position); } }); gridLayoutManager.setSpanCount(gridLayoutManager.getSpanCount()); } } public static void setFullSpan(RecyclerView.ViewHolder holder) { ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) { StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp; p.setFullSpan(true); } } } }

使用方法如下:

RecyclerView.Adapter homeExpertsAdapter = new HomeExpertsAdapter(new ArrayList<ResultBean>());
BaseHeaderAndFooterAdapter baseHeaderAndFooterAdapter = new BaseHeaderAndFooterAdapter(homeExpertsAdapter);

TextView textView = new TextView(getContext());
textView.setText("Header_1");
baseHeaderAndFooterAdapter.addHeaderView(textView);

recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
recyclerView.setAdapter(baseHeaderAndFooterAdapter);

相關推薦

[Android]自由新增HeadFootRecyclerView的Adapter

該Adapter能達到給RecyclerView自由新增Head和View的目的,且新增的Head和Foot不受LayouManager干擾,程式碼如下: public class BaseHeaderAndFooterAdapter<T> e

RecyclerView詳解(基本使用+解決複用+新增HEADFOOT+上拉載入更多+下拉重新整理)以及ExpandableListView的簡單使用

一、RecyclerView的簡單使用先看效果圖程式碼實現1.引入recyclerview包implementation 'com.android.support:design:27.1.0' 2.佈局中新增RecyclerView<?xml version="1.0"

Android SharedPreferences保存讀取

version editor amp byte corrupted share pty long [] SharedPreferences保存和讀取對象 1.首先要序列化對象(以下是序列化實體類的樣例,不方便貼出實體類全部的代碼) public clas

Android地圖新增標記文字【程式碼片段】

Android百度地圖SDK版本:5.2 1.建立並在專案中配置好AK; 2.Application中初始化地圖元件:SDKInitializer.initialize(mContext); 3.自己頁面中使用如下: <span style="font-family:Micros

Android應用新增(建立)刪除及判斷是否存在桌面快捷方式

Android桌面程式提供了應用新增和刪除桌面快捷方式的功能以及判斷快捷方式是否存在,只要傳入快捷方式標題、圖示及點選快捷方式執行的應用Intent即可。程式碼如下: /** * 為當前應用新增桌面快捷方式 * * @param cx * @param appNa

RecyclerView 新增head view頭部 foot view尾部、設定水平horizontal時左側佈局右側佈局

折騰一下午,遇到若干問題:如,設定水平HORIZONTAL時,佔用多個跨度(類似單元格的合併) 終於都好用了。。。 簡陋圖發6張。 LinearLayoutManager.VERTICAL LinearLayoutManager.HORIZONTAL

Android實現側滑-新增資料toolbar等功能

首先是主程式碼塊 package alice.bw.com.day01zhoukao; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.Fra

Android 新增選單返回按鈕

在toolbar上新增選單和返回按鈕 1. 新增選單 1.1 新建menu檔案 右擊res資料夾新建 Android resource dictionary,新建menu資料夾 右擊menu資料夾新建Menu resource file,輸入名稱 1.2 設定選單按鈕 &l

Android 完美實現圖片圓角圓形 實現進行分析

                轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/24555655本來想在網上找個圓角的例子看一看,不盡人意啊,基本都是官方的Demo的那張原理圖,稍後會貼出。於是自己自定義了個View,實現圖片的圓角以及圓形效

Android studio新增第三方庫so庫

原文: 以下兩種方式二選一 方法一: 1.在src/main中新建jniLibs資料夾 ,把.so複製進去即可 方法二: 1.在app/中新建libs資料夾,把.so複製進去 2.在app/build.gradle中新增以下五行指令碼即可(注:以下指令碼意思是會把

android 百度地圖系列之新增覆蓋物覆蓋物的點選事件

之前講了百度地圖定位和地圖基本操作,這篇部落格講一下,怎麼去給地圖新增覆蓋物,並當點選覆蓋物的時候顯示詳細資訊。 要給地圖新增覆蓋物,首先需要覆蓋物的經緯度,如果還要實現點選事件,顯示詳細的資訊,還需要覆蓋物的描述資訊(如圖片,位置名稱等),所以先新建一個實體

vb.net DataTable 新增賦值

       新增列:dtData.Columns.Add("XXX")       遍歷:          For Each row As DataRow In dtData.Rows           ‘獲取指定列的值             Dim aaa A

android studio 新增第三方libjar包 apk

新增第三方lib到apk 1. 將新增的lib copy到app下面的libs資料夾: 2. 在app下面的build.gradle中新增如下程式碼,注意要新增在android作用域下面,不然沒有作用: 新增framework.jar到apk: 1. 將android原

Retrofit,Okhttp每個Request統一動態新增header引數(五)

Header How to Add header to Every Request 新增統一通用header, 不會覆蓋前面的header okHttpClient.intercept

Android新增新的自定義鍵值按鍵處理流程

[cpp] view plain copy print? <span style="font-family:FangSong_GB2312;font-size:18px;">/*  * Copyright (C) 2010 The Android Open So

Android studio新增第三方庫so

原文: 以下兩種方式二選一 方法一: 1.在src/main中新建jniLibs資料夾 ,把.so複製進去即可 方法二: 1.在app/中新建libs資料夾,把.so複製進去 2.在app/build.gradle中新增以下五行指令碼即

Android開發之RecyclerView新增頭部底部

前言:我們在使用RecyclerView的過程中其實還是有很多問題的,前面提到的沒有預設的分割線,很是讓人蛋疼啊,但現在有出了個問題,不能新增頭部和底部,這一度讓我認為這貨還是沒有最愛的ListView好用啊,哈哈,既然谷歌出來了,我們就要使用,沒有頭和腳那我們就給他造出頭

[Android Studio] 向您的專案新增 C C++ 程式碼

搭配使用 Android Studio 2.2 或更高版本與 Android Plugin for Gradle 版本 2.2.0 或更高版本時,您可以將 C 和 C++ 程式碼編譯到 Gradle 與 APK 一起打包的原生庫中,將這類程式碼新增到您的應用中。您的 J

Android 簡捷地為RecyclerView新增HeadViewFootView

之前自己嘗試用ViewType的思路去實現為RecyclerView新增HeadView和FootView,總感覺自己寫的程式碼太囉嗦了,向兩位大神學習了一下他們的編碼思路寫了個簡單了些的,分享給大家。 廢話不多說,上圖上程式碼。 public class Recy

Android EditText 換行齊問題研究

1.原生方法換行Android textview換行屬性有BreakStrategy和hyphenationFrequencyandroid:breakStrategyBreak strategy (control over paragraph layout).Must be