Android L SDK发布的,新API中最有意思的就是RecyclerView (后面为RV) 和 CardView了, 按照官方的说法, RV 是一个ListView 的一个更高级更灵活的一个版本, 可以自定义的东西太多了。以前会不会觉得写一个Horizontal ListView 都觉得挺吃力的,但是如果你看过RV的话,你就会觉得这也太简单了吧。 废话不多,下面转入正题。
今天这里主要讲述的是 RV 简单用法:
1.跟ListView 一样 需要一个 Adapter
2.跟ListView 一样 需要一个 ViewHolder
3.有点不同了, 需要一个LayoutManager
详细过程看代码吧:
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 activity
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)", }; }
运行效果:
1) orientation = vertical
2) orientation = horizontal
RecyclerView还有很多高级自定义的东西, 例如ItemDecoration, Animator, LayoutManager里面的重写, 后续陆续给大家更新这方面的资料.
需要代码Demo的朋友可以留下邮箱.