Android RecyclerView 的簡單使用

  Android L SDK發佈的,新API中最有意思的就是RecyclerView (後面爲RV) 和 CardView了, 按照官方的說法, RV 是一個ListView 的一個更高級更靈活的一個版本, 能夠自定義的東西太多了。之前會不會以爲寫一個Horizontal ListView 都以爲挺吃力的,可是若是你看過RV的話,你就會以爲這也太簡單了吧。 廢話很少,下面轉入正題。 java

  今天這裏主要講述的是 RV 簡單用法:android

  1.跟ListView 同樣 須要一個 Adapterapp

  2.跟ListView 同樣 須要一個 ViewHolderide

  3.有點不一樣了, 須要一個LayoutManagerui

  詳細過程看代碼吧:this

 

  1 package com.jarrah.demo;
  2 
  3 import java.util.ArrayList;
  4 
  5 import android.os.Bundle;
  6 import android.support.v7.app.ActionBarActivity;
  7 import android.support.v7.widget.LinearLayoutManager;
  8 import android.support.v7.widget.RecyclerView;
  9 import android.view.View;
 10 import android.view.ViewGroup;
 11 
 12 public abstract class RecyclerViewActivity extends ActionBarActivity{
 13     
 14     
 15     protected RecyclerView mRecyclerView;
 16     protected Adapter<String> mAdapter;
 17     
 18     @Override
 19     protected void onCreate(Bundle savedInstanceState) {
 20         super.onCreate(savedInstanceState);
 21         mRecyclerView = new RecyclerView(this);
 22         setContentView(mRecyclerView);
 23         
 24         //配置RecyclerView 能夠提升執行效率, 前提你要知道有多少不變的item
 25         // use this setting to improve performance if you know that changes
 26         // in content do not change the layout size of the RecyclerView
 27         mRecyclerView.setHasFixedSize(true);
 28         
 29         //初始化適配器
 30         mAdapter = new Adapter<String>() {
 31 
 32             @Override
 33             public ViewHolder<String> onCreateViewHolder(ViewGroup group,
 34                     int position) {
 35                 return newViewHolder(group, position);
 36             }
 37             
 38         };
 39         
 40         mRecyclerView.setAdapter(mAdapter);
 41         
 42         //設置一個垂直方向的layout manager
 43         int orientation = LinearLayoutManager.VERTICAL;
 44         mRecyclerView.setLayoutManager(getLayoutManager(orientation));
 45     }
 46 
 47 
 48     protected LinearLayoutManager getLayoutManager(int orientation) {
 49         return new LinearLayoutManager(this, orientation, false);
 50     }
 51 
 52 
 53     
 54     /**
 55      * 實例化一個ViewHolder
 56      * @param group
 57      * @param position
 58      * @return
 59      */
 60     public abstract ViewHolder<String> newViewHolder(ViewGroup group, int position);
 61 
 62 
 63     public static abstract class Adapter<T> extends RecyclerView.Adapter<ViewHolder<T>> {
 64         
 65         private ArrayList<T> mList;
 66         
 67         public T getItem(int position) {
 68             return mList == null ? null : mList.get(position);
 69         }
 70         
 71         @Override
 72         public int getItemCount() {
 73             return mList == null ? 0 : mList.size();
 74         }
 75 
 76         @Override
 77         public void onBindViewHolder(
 78                 ViewHolder<T> vh, int position) {
 79             vh.onBind(getItem(position), vh.itemView);
 80         }
 81         
 82         public void setData(ArrayList<T> data) {
 83             mList = data;
 84             notifyDataSetChanged();
 85         }
 86     }
 87     
 88     public static abstract class ViewHolder<T> extends RecyclerView.ViewHolder {
 89         
 90         public ViewHolder(View v) {
 91             super(v);
 92         }
 93         
 94         /**
 95          * view holder 綁定數據
 96          * @param data
 97          * @param v
 98          */
 99         public abstract void onBind(T data, View v);
100         
101     }
102     
103 }

下面是demo activityspa

package com.jarrah.demo;

import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class DemoActivity extends RecyclerViewActivity{

    @Override
    public ViewHolder<String> newViewHolder(ViewGroup group, int position) {
        
        final TextView tv = new TextView(this);
        tv.setPadding(20, 20, 20, 20);
        tv.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String text = tv.getText().toString();
                Toast.makeText(DemoActivity.this, text, Toast.LENGTH_SHORT).show();
            }
        });
        
        ViewHolder<String> viewHolder = new ViewHolder<String>(tv) {
            
            @Override
            public void onBind(String data, View v) {
                TextView item = (TextView) v;
                item.setText(data);
            }
        };
        
        return viewHolder;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //設置數據
        ArrayList<String> data = new ArrayList<String>();
        data.addAll(Arrays.asList(sCheeses));
        mAdapter.setData(data);
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.demo, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //切換方向
        if (item.getItemId() == R.id.action_orientation) {
            LinearLayoutManager lm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            int orientation = lm.getOrientation() == 0 ? 1 : 0;
            mRecyclerView.setLayoutManager(getLayoutManager(orientation));
        }
        return super.onOptionsItemSelected(item);
    }
    
    public static final String[] sCheeses = {
         "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
         "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
         "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
         "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
         "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
         "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
         "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
         "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
         "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
         "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
         "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
         "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
         "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
         "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves",
         "Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur",
         "Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
         "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin",
         "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
         "Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
         "Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
         "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)",
         "Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta",
         "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
         "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat",
         "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano",
         "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain",
         "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou",
         "Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar",
         "Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno",
         "Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack",
         "Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
         "Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)",
         "Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese",
         "Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
         "Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley",
         "Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino",
         "Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
         "Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby",
         "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin",
         "Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
         "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue",
         "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz",
         "Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich",
         "Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue",
         "Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle",
         "Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia",
         "Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis",
         "Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus",
         "Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison",
         "Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois",
         "Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse",
         "Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese",
         "Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise",
         "Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra",
         "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
         "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
         "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
         "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve",
         "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
         "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti",
         "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve",
         "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
         "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg",
         "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
         "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
         "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese",
         "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere",
         "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire",
         "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou",
         "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
         "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings",
         "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse",
         "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam",
         "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego",
         "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
         "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)",
        
    };
    
}

運行效果:code

1) orientation = verticalorm

 

2)  orientation = horizontalblog

 

  RecyclerView還有不少高級自定義的東西, 例如ItemDecoration, Animator, LayoutManager裏面的重寫, 後續陸續給你們更新這方面的資料.

  須要代碼Demo的朋友能夠留下郵箱.

相關文章
相關標籤/搜索