Android控件详解之列表控件

来源:互联网 发布:大数据平台调度系统 编辑:程序博客网 时间:2024/06/08 03:11

我将Android控件的列表控件的学习知识总结一下和大家共享包括(ListView、ExpandableListView、Spinner)

在Android开发中,罗列信息或者整理信息就是需要用到进度控件,Android源生提供了ListView、ExpandableListView、Spinner这三种列表控件。

其中Spinner就是相当于windows上经常看到的下拉框。

1、ListView控件

(1)普通列表控件

ListView控件用于列表的形式显示数据。ListView控件采用MVC模式将前端显示与后端数据进行分离,也就是说,ListView控件在装载数据时并不是直接使用ListView.add或者类是的方法添加数据,而是需要指定一个Adapter对象,该对象就相当于MVC模式中的C(控制器,controller).ListView相当与MVC模式的V(视图,V),用于显示数据。为ListView提供数据的list、数组或数据库相当于MVC模式的M(模型、model)。

在ListView控件中通过Adapter对象获得需要显示的数据。在创建Adapter对象需要指定要显示的数据,因此,要显示的数据与ListView之间通过Adapter对象进行连接,同时,又互相独立。也就是说,ListView只知道显示的数据来自Adapter,并不知道这些数据是来自list、数据或者数据库。对于数据来说,只知道将数据添加到Adapter中,并不知道这些数据会被用于ListView或者其他控件。

ListView的属性:

1. 背景色:

listView设置背景色android:background="@drawable/bg",拖动或者点击list空白位置的时候发现ListItem都变成黑色。 因为默认的ListItem背景是透明的,而ListView的背景是固定不变的,所以在滚动条滚动的过程中如果实时地去将当前每个Item的显示内容跟背景进行混合运算,所以android系统为了优化这个过程用,就使用了一个叫做android:cacheColorHint的属性,在黑色主题下默认的颜色值是#191919,所以就出现了刚才的画面,有一半是黑色的。

如果你只是换背景的颜色的话,可以直接指定android:cacheColorHint为你所要的颜色;如果你是用图片做背景的话,那也只要将android:cacheColorHint指定为透明(#00000000)就可以了,当然为了美化是要牺牲一些效率的。

2. android:fadingEdge="none" 去掉上边和下边黑色的阴影

3. android:divider="@drawable/list_driver" 其中 @drawable/list_driver 是一个图片资源lsitview的每一项之间需要设置一个图片做为间隔

设置Item之间无间隙

android:divider="#00000000" 或者在javaCode中如下定义:listView.setDividerHeight(0);

4. android:listSelector="@color/pink" listView item 选中时的颜色。默认为橙黄底色。

5. android:divider="@drawable/list_driver" 设置分割线的图片资源,如果则只要设置为

android:divider="@drawable/@null" 不想显示分割线

 

6. android:scrollbars="none" setVerticalScrollBarEnabled(true); 隐藏listView的滚动条

7. android:fadeScrollbars="true" 设置为true就可以实现滚动条的自动隐藏和显示

8. android:transcriptMode="alwaysScroll" 用ListView或者其它显示大量Items的控件实时跟踪或者查看信息,希望最新的条目可以自动滚动到可视范围内。通过设置的控件transcriptMode属性可以将Android平台的控件(支持ScrollBar)自动滑动到最底部。

android:fastScrollEnabled="false"
android:fastScrollEnabled = "true" 加快滑动速度、滚动滑杆(至少要有4个滚动页)

android:drawSelectorOnTop="false" 
android:scrollingCache="false" 

android:drawSelectorOnTop="true" 点击某一条记录,颜色会显示在最上面,记录上的文字被遮住,所以点击文字不放,文字就看不到

android:drawSelectorOnTop="false" 点击某条记录不放,颜色会在记录的后面,成为背景色,但是记录内容的文字是可见的

When set to true, the selector will be drawn over the selected item. Otherwise the selector is drawn behind the selected item. The default value is false.

9.在ListView中添加属性:
android:scrollbarTrackVertical="@drawable/scrollbar_vertical_track" android:scrollbarThumbVertical="@drawable/scrollbar_vertical_thumb"
scrollbar_vertical_track,crollbar_vertical_thumb自定义的xml文件,放在Drawable中,track是指长条,thumb是指短条,然后再xml中定义短条和长条的样式



下面一个例子:

布局文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><ListView android:id="@+id/lvCommonListView"android:layout_width="fill_parent" android:layout_height="wrap_content" android:fastScrollEnabled="true"/></LinearLayout>

Main.java:

public class Main extends Activity implements OnItemSelectedListener,OnItemClickListener{private static String[] data = new String[]{"天地逃生","保持通话","乱世佳人(飘)","怪侠一枝梅","第五空间","孔雀翎","变形金刚3(真人版)","星际传奇" };@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id)                       //列表项被点击触发{Log.d("itemclick", "click " + position + " item");}@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position,long id)                         //用于监听列表项被选中触发{Log.d("itemselected", "select " + position + " item");}@Overridepublic void onNothingSelected(AdapterView<?> parent){Log.d("nothingselected", "nothing selected");}@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);ListView lvCommonListView = (ListView) findViewById(R.id.lvCommonListView);ArrayAdapter<String> aaData = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data);              //后两个参数分别指定布局资源和数据lvCommonListView.setAdapter(aaData);        lvCommonListView.setOnItemClickListener(this);lvCommonListView.setOnItemSelectedListener(this);}}

ListActivity.java:

public class ListViewActivity extends Activity{private String[] items ={ "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)", "Mascarpone Torta","Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse","Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)","Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette","Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo","Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio","Monterey Jack", "Monterey Jack Dry", "Morbier","Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella","Mozzarella (Australian)", "Mozzarella di Bufala","Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster","Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais","Neufchatel", "Neufchatel (Australian)", "Niolo", "Nokkelost","Northumberland", "Oaxaca", "Olde York", "Olivet au Foin","Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar","Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty", "Oszczypek","Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer","Panela", "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)","Parmigiano Reggiano", "Pas de l'Escalette", "Passendale","Pasteurized Processed", "Pate de Fromage", "Patefine Fort","Pave d'Affinois", "Pave d'Auge", "Pave de Chirac","Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves","Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes","Pelardon des Corbieres", "Penamellera", "Penbryn", "Pencarreg","Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse","Picodon de Chevre", "Picos de Europa", "Piora","Pithtviers au Foin", "Plateau de Herve", "Plymouth Cheese","Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque","Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre","Pourly", "Prastost", "Pressato", "Prince-Jean","Processed Cheddar", "Provolone", "Provolone (Australian)","Pyengana Cheddar", "Pyramide", "Quark", "Quark (Australian)","Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit","Queso Blanco", "Queso Blanco con Frutas --Pina y Mango","Queso de Murcia", "Queso del Montsec", "Queso del Tietar","Queso Fresco", "Queso Fresco (Adobera)", "Queso Iberico","Queso Jalapeno", "Queso Majorero", "Queso Media Luna","Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette","Ragusano", "Raschera", "Reblochon", "Red Leicester","Regal de la Dombes", "Reggianito", "Remedou", "Requeson","Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata","Ridder", "Rigotte", "Rocamadour", "Rollot", "Romano","Romans Part Dieu", "Roncal", "Roquefort", "Roule","Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu","Saaland Pfarr", "Saanenkaese", "Saga", "Sage Derby","Sainte Maure", "Saint-Marcellin", "Saint-Nectaire","Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre","Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza","Schabzieger", "Schloss", "Selles sur Cher", "Selva", "Serat","Seriously Strong Cheddar", "Serra da Estrela", "Sharpam","Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene","Smoked Gouda", "Somerset Brie", "Sonoma Jack","Sottocenare al Tartufo", "Soumaintrain", "Sourire Lozerien","Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese","Stilton", "Stinking Bishop", "String", "Sussex Slipcote","Sveciaost", "Swaledale", "Sweet Style Swiss", "Swiss","Syrian (Armenian String)", "Tala", "Taleggio", "Tamie","Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea","Testouri", "Tete de Moine", "Tetilla", "Texas Goat Cheese","Tibet", "Tillamook Cheddar", "Tilsit", "Timboon Brie", "Toma","Tomme Brulee", "Tomme d'Abondance", "Tomme de Chevre","Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans","Tommes", "Torta del Casar", "Toscanello", "Touree de L'Aubier","Tourmalet", "Trappe (Veritable)", "Trois Cornes De Vendee","Tronchon", "Trou du Cru", "Truffe", "Tupi", "Turunmaa","Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa","Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco","Vendomois", "Vieux Corse", "Vignotte", "Vulscombe","Waimata Farmhouse Blue", "Washed Rind Cheese (Australian)","Waterloo", "Weichkaese", "Wellington", "Wensleydale","White Stilton", "Whitestone Farmhouse", "Wigmore","Woodside Cabecou", "Xanadu", "Xynotyro", "Yarg Cornish","Yarra Valley Pyramid", "Yorkshire Blue", "Zamorano","Zanetti Grana Padano", "Zanetti Parmigiano Reggiano" };/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);ListView listView = (ListView) findViewById(R.id.lvCommonListView);listView.setAdapter(new BaseAdapter(){@Overridepublic View getView(int position, View convertView, ViewGroup parent){TextView textView = new TextView(ListViewActivity.this);textView.setText(items[position]);return textView;}@Overridepublic long getItemId(int position){return position;}@Overridepublic Object getItem(int position){return items[position];}@Overridepublic int getCount(){return items.length;}});}}
(2)为ListView列表添加复选框和选项按钮

只看看下面的例子:

布局文件:

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="CheckedTextView"android:background="#FFF" android:textColor="#000" android:gravity="center" /><ListView android:id="@+id/lvCheckedTextView"android:layout_width="fill_parent" android:layout_height="wrap_content" /><TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="RadioButton"android:background="#FFF" android:textColor="#000" android:gravity="center"  /><ListView android:id="@+id/lvRadioButton"android:layout_width="fill_parent" android:layout_height="wrap_content" /><TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="CheckBox"android:background="#FFF" android:textColor="#000" android:gravity="center"  /><ListView android:id="@+id/lvCheckBox" android:layout_width="fill_parent"android:layout_height="wrap_content" /></LinearLayout></span><span style="font-size:18px;"></span>
java实现文件:

public class Main extends Activity{/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);ListView lvCheckedTextView = (ListView) findViewById(R.id.lvCheckedTextView);ListView lvRadioButton = (ListView) findViewById(R.id.lvRadioButton);ListView lvCheckBox = (ListView) findViewById(R.id.lvCheckBox);String[] data = new String[]{ "Android", "Meego" };ArrayAdapter<String> aaCheckedTextViewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, data);lvCheckedTextView.setAdapter(aaCheckedTextViewAdapter);lvCheckedTextView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);             //设置选择模式(单多选)// ArrayAdapter<String> aaCheckedTextViewAdapter = new// ArrayAdapter<String>(this, android.R.layout.simple_list_item_2,// android.R.id.text2,data);// lvCheckedTextView.setAdapter(aaCheckedTextViewAdapter);// lvCheckedTextView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);ArrayAdapter<String> aaRadioButtonAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, data);lvRadioButton.setAdapter(aaRadioButtonAdapter);lvRadioButton.setChoiceMode(ListView.CHOICE_MODE_SINGLE);ArrayAdapter<String> aaCheckBoxAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, data);lvCheckBox.setAdapter(aaCheckBoxAdapter);lvCheckBox.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);}}
(3)对列表的增、删、改操作

这边主要是自己去实现Adapter,需要继承android.widget.BaseAdapter类。两个比较重要的方法getView和getCount(返回显示的列表的View对象和显示总数)
例子:

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayout android:orientation="horizontal"android:layout_width="fill_parent" android:layout_height="wrap_content"><Button android:id="@+id/btnAddText" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="添加文本" /><Button android:id="@+id/btnAddImage" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="添加图像" /><Button android:id="@+id/btnRemove" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="删除当前项" /></LinearLayout><LinearLayout android:orientation="horizontal"android:layout_width="fill_parent" android:layout_height="wrap_content"><Button android:id="@+id/btnModify" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="随机修改当前项" /><Button android:id="@+id/btnRemoveAll" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="清空" /></LinearLayout><ListView android:id="@+id/lvDynamic" android:layout_width="fill_parent"android:layout_height="fill_parent" android:cacheColorHint="#00000000" /></LinearLayout>
image.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="wrap_content"><ImageView android:id="@+id/imageview" android:layout_width="100dp"android:layout_height="100dp" android:padding="10dp"/></LinearLayout>
text.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="wrap_content"><TextView android:id="@+id/textview" android:layout_width="fill_parent"android:layout_height="wrap_content" android:padding="10dp"android:textAppearance="?android:attr/textAppearanceLarge" /></LinearLayout>
main.java

public class Main extends Activity implements OnClickListener,OnItemSelectedListener{private static String[] data = new String[]{"天地逃生","保持通话","乱世佳人(飘)","怪侠一枝梅","第五空间","孔雀翎","变形金刚3(真人版)","星际传奇","《大笑江湖》剧中,小鞋匠是小沈阳,他常强出头,由不懂武功的菜鸟变成武林第一高手;赵本山则是个武功高强的大盗,被不会武功的小沈阳打败;程野扮演赵本山的手下皮丘,经常拖累赵本山。 其余角色都围绕小沈阳设置。" };private ListView lvDynamic;private ViewAdapter viewAdapter;private int selectedIndex = -1;private class ViewAdapter extends BaseAdapter{private Context context;private List textIdList = new ArrayList();@Overridepublic View getView(int position, View convertView, ViewGroup parent){String inflater = Context.LAYOUT_INFLATER_SERVICE;LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);LinearLayout linearLayout = null;if (textIdList.get(position) instanceof String){linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.text, null);TextView textView = ((TextView) linearLayout.findViewById(R.id.textview));textView.setText(String.valueOf(textIdList.get(position)));}else if (textIdList.get(position) instanceof Integer){linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.image, null);ImageView imageView = (ImageView) linearLayout.findViewById(R.id.imageview);imageView.setImageResource(Integer.parseInt(String.valueOf(textIdList.get(position))));}return linearLayout;}public ViewAdapter(Context context){this.context = context;}@Overridepublic long getItemId(int position){return position;}@Overridepublic int getCount(){return textIdList.size();}@Overridepublic Object getItem(int position){return textIdList.get(position);}public void addText(String text){textIdList.add(text);notifyDataSetChanged();}public void addImage(int resId){textIdList.add(resId);notifyDataSetChanged();}public void remove(int index){if (index < 0)return;textIdList.remove(index);notifyDataSetChanged();}public void modify(int index, String text){if (index < 0)return;if (textIdList.get(index) instanceof String){textIdList.set(index, text);notifyDataSetChanged();}}public void removeAll(){textIdList.clear();notifyDataSetChanged();}}private int getImageResourceId(){int[] resourceIds = new int[]{ R.drawable.item1, R.drawable.item2, R.drawable.item3,R.drawable.item4, R.drawable.item5 };return resourceIds[new Random().nextInt(resourceIds.length)];}@Overridepublic void onClick(View view){switch (view.getId()){case R.id.btnAddText:int randomNum = new Random().nextInt(data.length);viewAdapter.addText(data[randomNum]);break;case R.id.btnAddImage:viewAdapter.addImage(getImageResourceId());break;case R.id.btnRemove:viewAdapter.remove(selectedIndex);selectedIndex = -1;break;case R.id.btnModify:viewAdapter.modify(selectedIndex,data[new Random().nextInt(data.length)]);selectedIndex = -1;break;case R.id.btnRemoveAll:viewAdapter.removeAll();break;}}@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position,long id){selectedIndex = position;}@Overridepublic void onNothingSelected(AdapterView<?> parent){// TODO Auto-generated method stub}@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);lvDynamic = (ListView) findViewById(R.id.lvDynamic);Button btnAddText = (Button) findViewById(R.id.btnAddText);Button btnAddImage = (Button) findViewById(R.id.btnAddImage);Button btnRemove = (Button) findViewById(R.id.btnRemove);Button btnModify = (Button) findViewById(R.id.btnModify);Button btnRemoveAll = (Button) findViewById(R.id.btnRemoveAll);btnAddText.setOnClickListener(this);btnAddImage.setOnClickListener(this);btnRemove.setOnClickListener(this);btnModify.setOnClickListener(this);btnRemoveAll.setOnClickListener(this);viewAdapter = new ViewAdapter(this);lvDynamic.setAdapter(viewAdapter);lvDynamic.setOnItemSelectedListener(this);}}
这边强调一下getview方法,ListView会根据当前可视的列表项决定什么时候调用给View方法,调用几次geiview方法。比如:ListView有1000项,但是getview方法并不会调用1000次,而是根据当前屏幕上可见或即将显示的列表项调用。

(4)改变列表项的背景色

直接看例子:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><RadioGroup android:layout_width="wrap_content"android:layout_height="wrap_content"><RadioButton android:id="@+id/rbdefault"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="默认颜色" android:checked="true"/><RadioButton android:id="@+id/rbGreen"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="绿色" /><RadioButton android:id="@+id/rbSpectrum"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="光谱" /></RadioGroup><ListView android:id="@+id/listview" android:layout_width="fill_parent"android:layout_height="wrap_content" /> </LinearLayout>
java代码:

public class Main extends Activity implements OnClickListener

{private Drawable defaultSelector;private ListView listView;@Overridepublic void onClick(View view){switch (view.getId()){case R.id.rbdefault:listView.setSelector(defaultSelector);   //改变背景色方法break;case R.id.rbGreen:listView.setSelector(R.drawable.green);break;case R.id.rbSpectrum:listView.setSelector(R.drawable.spectrum);break;}}@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);String[] data = new String[]{ "计算机", "英语", "物理", "化学" };ArrayAdapter<String> aaAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data);listView = (ListView) findViewById(R.id.listview);listView.setAdapter(aaAdapter);defaultSelector = listView.getSelector();RadioButton rbDefault = (RadioButton) findViewById(R.id.rbdefault);rbDefault.setNextFocusDownId(R.id.listview);rbDefault.setOnClickListener(this);RadioButton rbGreen = (RadioButton) findViewById(R.id.rbGreen);rbGreen.setNextFocusDownId(R.id.listview);rbGreen.setOnClickListener(this);RadioButton rbSpectrum = (RadioButton) findViewById(R.id.rbSpectrum);rbSpectrum.setNextFocusDownId(R.id.listview);rbSpectrum.setOnClickListener(this);}}
2、ExpandableListView控件

ExpandableListView控件为可扩展列表控件,是ListView的子类。同样也需要一个Adapter,继承BaseExpandableListAdapter,其中两个核心的方法:getGroupView和getChildView

下面一个例子:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /></LinearLayout>
public class Main extends ExpandableListActivity{@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);ExpandableListAdapter adapter = new MyExpandableListAdapter();setListAdapter(adapter);registerForContextMenu(getExpandableListView());}@Overridepublic void onCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo){ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;int type = ExpandableListView.getPackedPositionType(info.packedPosition);String title = ((TextView) info.targetView).getText().toString();if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD){menu.setHeaderTitle("弹出菜单");menu.add(0, 0, 0, title);}}@Overridepublic boolean onContextItemSelected(MenuItem item){ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();String title = ((TextView) info.targetView).getText().toString();Toast.makeText(this, title, Toast.LENGTH_SHORT).show();return true;}public class MyExpandableListAdapter extends BaseExpandableListAdapter{private String[] provinces ={ "辽宁", "山东", "江西", "四川" };private String[][] cities ={{ "沈阳", "大连", "鞍山", "抚顺" },{ "济南", "青岛", "淄博", "枣庄" },{ "南昌", "景德镇" },{ "成都", "自贡", "攀枝花" } };public Object getChild(int groupPosition, int childPosition){return cities[groupPosition][childPosition];}public long getChildId(int groupPosition, int childPosition){return childPosition;}public int getChildrenCount(int groupPosition){return cities[groupPosition].length;}public TextView getGenericView(){AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 64);TextView textView = new TextView(Main.this);textView.setLayoutParams(lp);textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);textView.setPadding(36, 0, 0, 0);textView.setTextSize(20);return textView;}public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent){if(convertView == null)convertView = getGenericView();TextView textView = (TextView) convertView;textView.setText(getChild(groupPosition, childPosition).toString());return textView;}public Object getGroup(int groupPosition){return provinces[groupPosition];}public int getGroupCount(){return provinces.length;}public long getGroupId(int groupPosition){return groupPosition;}public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent){if(convertView == null)convertView = getGenericView();TextView textView = (TextView) convertView;textView.setText(getGroup(groupPosition).toString());return textView;}public boolean isChildSelectable(int groupPosition, int childPosition){return true;}public boolean hasStableIds(){return true;}}}
3、Spinner控件
Spinner控件是一个下拉的列表控件,该控件用法与ListView控件类似,在转载数据也是需要一个Adapter对象。

看例子:

main.xml;

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><Spinner android:id="@+id/spinner1" android:layout_width="fill_parent"android:layout_height="wrap_content" /><Spinner android:id="@+id/spinner2" android:layout_width="fill_parent"android:layout_height="wrap_content" android:layout_marginTop="20dp"/></LinearLayout>
item.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="wrap_content"><ImageView android:id="@+id/ivLogo" android:layout_width="60dp"android:layout_height="60dp" android:src="@drawable/icon"android:paddingLeft="10dp" /><TextView android:id="@+id/tvApplicationName" android:textColor="#000"android:layout_width="wrap_content" android:layout_height="fill_parent"android:textSize="16dp" android:gravity="center_vertical"android:paddingLeft="10dp" /></LinearLayout>
java实现;

public class Main extends Activity{@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);String[] mobileOS = new String[]{ "Android", "IPhone", "Symbian", "Meego", "Window Phone7" };ArrayAdapter<String> aaAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mobileOS);// 将上如下代码可以使列表项带RadioButton控件// aaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);spinner1.setAdapter(aaAdapter);Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);final List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();Map<String, Object> item1 = new HashMap<String, Object>();item1.put("ivLogo", R.drawable.calendar);item1.put("tvApplicationName", "多功能日历");Map<String, Object> item2 = new HashMap<String, Object>();item2.put("ivLogo", R.drawable.eoemarket);item2.put("tvApplicationName", "eoeMarket客户端");items.add(item1);items.add(item2);SimpleAdapter simpleAdapter = new SimpleAdapter(this, items,R.layout.item, new String[]{ "ivLogo", "tvApplicationName" }, new int[]{ R.id.ivLogo, R.id.tvApplicationName });spinner2.setAdapter(simpleAdapter);spinner2.setOnItemSelectedListener(new OnItemSelectedListener(){@Overridepublic void onItemSelected(AdapterView<?> parent, View view,int position, long id){setTitle(items.get(position).get("tvApplicationName").toString());}@Overridepublic void onNothingSelected(AdapterView<?> parent){
}});}}

以上是个人对列表控件的一些知识总结,欢迎大家阅读指点。


0 0