Android L SDK發布的,新API中最有意思的就是RecyclerView (後面為RV) 和 CardView了, 按照官方的說法, RV 是一個ListView 的一個更高級更靈活的一個版本, 可以自定義的東西太多了。以前會不會覺得寫一個Horizontal ListView 都覺得挺吃力的,但是如果你看過RV的話,你就會覺得這也太簡單了吧。 廢話不多,下面轉入正題。
今天這裡主要講述的是 RV 簡單用法:
1.跟ListView 一樣 需要一個 Adapter
2.跟ListView 一樣 需要一個 ViewHolder
3.有點不同了, 需要一個LayoutManager
詳細過程看代碼吧:
package com.jarrah.demo;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
public abstract class RecyclerViewActivity extends ActionBarActivity{
protected RecyclerView mRecyclerView;
protected Adapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRecyclerView = new RecyclerView(this);
setContentView(mRecyclerView);
//配置RecyclerView 可以提高執行效率, 前提你要知道有多少不變的item
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
//初始化適配器
mAdapter = new Adapter<String>() {
@Override
public ViewHolder<String> onCreateViewHolder(ViewGroup group,
int position) {
return newViewHolder(group, position);
}
};
mRecyclerView.setAdapter(mAdapter);
//設置一個垂直方向的layout manager
int orientation = LinearLayoutManager.VERTICAL;
mRecyclerView.setLayoutManager(getLayoutManager(orientation));
}
protected LinearLayoutManager getLayoutManager(int orientation) {
return new LinearLayoutManager(this, orientation, false);
}
/**
* 實例化一個ViewHolder
* @param group
* @param position
* @return
*/
public abstract ViewHolder<String> newViewHolder(ViewGroup group, int position);
public static abstract class Adapter<T> extends RecyclerView.Adapter<ViewHolder<T>> {
private ArrayList<T> mList;
public T getItem(int position) {
return mList == null ? null : mList.get(position);
}
@Override
public int getItemCount() {
return mList == null ? 0 : mList.size();
}
@Override
public void onBindViewHolder(
ViewHolder<T> vh, int position) {
vh.onBind(getItem(position), vh.itemView);
}
public void setData(ArrayList<T> data) {
mList = data;
notifyDataSetChanged();
}
}
public static abstract class ViewHolder<T> extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
}
/**
* view holder 綁定數據
* @param data
* @param v
*/
public abstract void onBind(T data, View v);
}
}
下面是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裡面的重寫, 後續陸續給大家更新這方面的資料.
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11