android listview 替代品recyclerview詳解

来源:http://www.cnblogs.com/peng-chenguang/archive/2016/07/15/5674109.html
-Advertisement-
Play Games

安卓v7支持包下的ListView替代品————RecyclerView RecyclerView這個控制項也出來很久了,相信大家也學習的差不多了,如果還沒學習的,或許我可以帶領大家體驗一把這個藝術般的控制項。 據官方介紹,該控制項是屬於之間用的非常多的ListView和GridView的替代品,既然能替 ...


安卓v7支持包下的ListView替代品————RecyclerView

 

RecyclerView這個控制項也出來很久了,相信大家也學習的差不多了,如果還沒學習的,或許我可以帶領大家體驗一把這個藝術般的控制項。

據官方介紹,該控制項是屬於之間用的非常多的ListView和GridView的替代品,既然能替代用的如此普遍的它們,這自然有其該有的優勢。

1)相對於ListView而言RecyclerView的優勢體現在:

①封裝了之前ListView的優化,封裝了之前ViewHolder的復用,這樣在自定義適配器的時候我們面向的不再是View,而是一個ViewHolder.

②提供了插板式的體驗,高度解耦,異常靈活,針對每一項的顯示抽取出了相應的類來控制每一個item的顯示。若想實現網格視圖或者瀑布流或者橫向的ListView都可以通過制定不一樣的LayoutManager來實現高大上的效果,這樣就可以針對自己的業務邏輯隨意發揮了。

③現在的RecyclerView對增刪也有了動畫的加入,並且你還可以自定義這些動畫。

④對於Adaper適配器,現在刷新也增加了相應的方法,雖然之前的notifyDataSetChanged()同樣可以實現這樣的效果,但是每次刷新整個界面在數據多的時候必然會大大影響用戶體驗。所以Adapter增加了更新數據的方法notifyItemInserted和notifyItemRemoved,這樣就可以在增刪數據的時候只刷新被操作的Item,而且還加入了高大上的動畫效果呢。

2)基本用法:

相信描述了這麼多,你一定對這個神奇的控制項迫不及待想嘗試一波了。要用到這個RecyclerView很簡單,首先在Gradle中添加支持包:

1 compile 'com.android.support:recyclerview-v7:24.0.0'

下麵就先來一個簡單的用法,首先來Activity

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 package com.example.nanchen.recyclerviewdemo;   import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Toast;   import java.util.ArrayList; import java.util.List; import java.util.Locale;   public class MainActivity extends AppCompatActivity implements MyAdapter.OnRecyclerItemClickListener {       private MyAdapter adapter;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);           RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recycler);         List<String> list = new ArrayList<>();         for (int i = 0; i < 100; i++) { //            list.add(String.format(Locale.CHINA, "第%03d條數據%s", i, i % 2 == 0 ? "" : "-----------------------"));             list.add(String.format(Locale.CHINA, "第%03d條數據", i));         }         adapter = new MyAdapter(this, list);         adapter.setOnRecyclerItemClickListener(this);         recyclerView.setAdapter(adapter);           DefaultItemAnimator animator = new DefaultItemAnimator();         animator.setRemoveDuration(1000);         recyclerView.setItemAnimator(animator);         //recyclerView.addItemDecoration(new MyDividerItemDecoration(this,MyDividerItemDecoration.VERTICAL_LIST));           //最後一個參數是反轉佈局一定是false,為true的時候為逆向顯示,在聊天記錄中可能會有使用         //這個東西在顯示後才會載入,不會像ScollView一樣一次性載入導致記憶體溢出         LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);         recyclerView.setLayoutManager(layoutManager);           //        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);         //        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {         //            @Override         //            public int getSpanSize(int position) {         //                if (position == 0){         //                    return 3;         //                }         //                return 1;         //            }         //        });         //        recyclerView.setLayoutManager(gridLayoutManager);   //        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); //        recyclerView.setLayoutManager(staggeredGridLayoutManager);     }       @Override     public void OnRecyclerItemClick(RecyclerView parent, View view, int position, String data) {         Toast.makeText(this, data, Toast.LENGTH_SHORT).show();         adapter.remove(position);     } }

  在上面的Activity代碼中,可見,我們需要自己指定LayoutManager,代碼中用的是LinearLayoutMagener,你可以試試其他的。

再看看Adapter,有一個對大多數人來說很悲催的是,我們的ListView中一定會有的點擊事件,而RecyclerView並沒有提供這樣的方法,這些點擊事件都是需要我們自己學的,我這裡Adapter就簡單的實現了下,點擊就會刪除該Item。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 package com.example.nanchen.recyclerviewdemo;   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.TextView;   import java.util.List;   /**  * 自定義RecyclerView的Adapter  * Created by 南塵 on 16-7-15.  */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {       private Context context;     private List<String> list;     private OnRecyclerItemClickListener listener;     private RecyclerView recyclerView;       public void setOnRecyclerItemClickListener(OnRecyclerItemClickListener listener) {         this.listener = listener;     }       public MyAdapter(Context context, List<String> list) {         this.context = context;         this.list = list;     }       //在為RecyclerView提供數據的時候調用     @Override     public void onAttachedToRecyclerView(RecyclerView recyclerView) {         super.onAttachedToRecyclerView(recyclerView);         this.recyclerView = recyclerView;     }       @Override     public void onDetachedFromRecyclerView(RecyclerView recyclerView) {         super.onDetachedFromRecyclerView(recyclerView);         this.recyclerView = null;     }       @Override     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View view = LayoutInflater.from(context).inflate(R.layout.item,parent,false);         view.setOnClickListener(this);         return new ViewHolder(view);     }       @Override     public void onBindViewHolder(ViewHolder holder, int position) {         holder.text.setText(list.get(position));     }       @Override     public int getItemCount() {         return list.size();     }       @Override     public void onClick(View v) {         if (recyclerView != null && listener != null){             int position = recyclerView.getChildAdapterPosition(v);             listener.OnRecyclerItemClick(recyclerView,v,position,list.get(position));         }     }       /**      * 刪除指定數據      * @param position 數據位置      */     public void remove(int position){         list.remove(position); //        notifyDataSetChanged();         notifyItemRemoved(position);//這樣就只會刪除這一條數據,而不會一直刷       }       /**      * 插入數據      * @param position 插入位置      * @param data 插入的數據      */     public void insert(int position,String data){         list.add(position,data);         notifyItemInserted(position);       }       public static class ViewHolder extends RecyclerView.ViewHolder{           private final TextView text;           public ViewHolder(View itemView) {             super(itemView);             text = (TextView) itemView.findViewById(R.id.item_text);         }     }         /**      * 自定義RecyclerView的點擊事件      */     interface OnRecyclerItemClickListener{         void OnRecyclerItemClick(RecyclerView parent,View view,int position,String data);     }   }

  繼承這個Adapter需要指定一個ViewHolder的泛型,當然這個ViewHolder通常是由我們作為一個靜態類自己寫的。其他這個就像我們之前ListView中的BaseAdapter一樣。

自己還可以實現其他的點擊事件。

下麵看下Xml,第一個是主佈局,第二個是每一個項的佈局,我這裡就簡單隻實現一個TextView了。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context="com.example.nanchen.recyclerviewdemo.MainActivity">       <android.support.v7.widget.RecyclerView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/main_recycler"/>   </RelativeLayout>

  

1 2 3 4 5 6 7 8 9 10 11 12 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"               android:layout_width="match_parent"               android:layout_height="wrap_content"               android:orientation="vertical">       <TextView         android:id="@+id/item_text"         android:textSize="30sp"         android:layout_width="match_parent"         android:layout_height="match_parent"/> </LinearLayout>

  這樣運行出來你估計就會看到沒有分割線,那麼分割線怎麼弄呢,看下文檔,需要我們自己去寫,這個網上有很多。

上一個我看到過很多次的。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 package com.example.nanchen.recyclerviewdemo;   import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View;   /**  * Created by 南塵 on 16-7-15.  */ public class MyDividerItemDecoration extends RecyclerView.ItemDecoration {     private static final int[] ATTRS = new int[]{             android.R.attr. listDivider     };       public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;       public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;       private Drawable mDivider;       private int mOrientation;       public MyDividerItemDecoration(Context context, int orientation) {         final TypedArray a = context.obtainStyledAttributes(ATTRS );         mDivider = a.getDrawable(0);         a.recycle();         setOrientation(orientation);     }       public void setOrientation( int orientation) {         if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {             throw new IllegalArgumentException( "invalid orientation");         }         mOrientation = orientation;     }       @Override     public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {         if (mOrientation == VERTICAL_LIST) {             drawVertical(c, parent);
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、line-height的定義 line-height,行高,是指文本行基線間的垂直距離。 1. 什麼是基線? 一般而言,一個文本行一共有四條線,從上到下依次為頂線、中線、基線、底線;在英文中,基線為小寫 x 字母下邊緣所在的那條線。如圖: 註意,基線的位置與字體有關,不同的字體基線的位置有偏差。 ...
  • HTML可以看成是由節點(node)組成的樹結構 我們一般都是在<p>節點裡面寫字元串。 在上圖中,<p>節點和字元串之間有一個text, 這個text就是文本節點。 我們可以這樣創建文本節點 document.createTextNode(String); 我們也可以把他添加到<p>節點 var ...
  • 做的一個項目中需要得到經緯度.. 實現:先寫一個方法如下 在直接用就可以了 第一個參數是地名,第二個參數是城市名,第三個是你想在哪個文本框顯示...就可以得到文本框的值也就是該地名.. 最後就是取文本框的值,如果不想看到這個文本框,可以隱藏,同樣可以取到值 ...
  • (?:pattern) 匹配 pattern 但不獲取匹配結果,也就是說這是一個非獲取匹配,不進行存儲供以後使用。這在使用 "或" 字元 (|) 來組合一個模式的各個部分是很有用。例如, 'industr(?:y|ies) 就是一個比 'industry|industries' 更簡略的表達式。 ( ...
  • × 目錄 [1]表達式 [2]塊語句 [3]空語句[4]聲明 前面的話 如果表達式在javascript中是短語,那麼語句(statement)就是javascript整句或命令。表達式計算出一個值,語句用來執行以使某件事發生。javascript程式無非就是一系列可執行語句的集合,javascri ...
  • TWaver能否與其他開發工具集成?當然沒有問題!今天就拿一個EasyUI的小例子試刀,小小演示一下如何在其上添加TWaver圖元。原例展示了一個EasyUI的基本佈局,併在其中部面板添加了表格。我們的目標是在其表格上方添加個簡單的TWaver拓撲圖,並將其樹圖顯示在west面板。 ...
  • 我也是看了騰訊isux的博客,解答了我關於flexbox一個很長時間的疑惑,就是flex佈局在安卓手機會出現內容長短不同導致不均分的現象。 具體的內容可以去看騰訊isux的博客,地址在這:https://isux.tencent.com/flexbox.html 我這裡也只是當作一個問題的紀錄 其實 ...
  • 線上實例 實例演示 預設 實例演示 每周第一天 實例演示 輸入框插件 實例演示 HTML data 屬性 實例演示 回調函數1 實例演示 回調函數2 使用方法 複製 複製 下載 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...