Android ListView實(shí)現(xiàn)單選及多選等功能示例
本文實(shí)例講述了Android ListView實(shí)現(xiàn)單選及多選等功能的方法。分享給大家供大家參考,具體如下:
在項(xiàng)目中也遇到過給ListView的item添加選擇功能。比如一個(gè)網(wǎng)購(gòu)APP,有個(gè)歷史瀏覽頁面,這個(gè)頁面現(xiàn)點(diǎn)擊item單選/多選及全選刪除功能。
當(dāng)時(shí)也是通過在數(shù)據(jù)中添加一個(gè)是否選擇的字段來記錄item的狀態(tài),然后根據(jù)這個(gè)字段有相應(yīng)的position位置進(jìn)行選擇狀態(tài)更改及刪除操作。
剛剛看了Android API Demos中17種ListView的實(shí)現(xiàn)方法,發(fā)現(xiàn)ListView自身就帶有我們所需要的單選,多選功能而且實(shí)現(xiàn)起來相當(dāng)方便。
/** * 單選或多選功能ListView * @description: * @author ldm * @date 2016-4-21 上午10:44:37 */ public class SingleChoiceList extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);//添加這一句話,就實(shí)現(xiàn)單選功能 //listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);//添加這一句話,就實(shí)現(xiàn)多選功能 } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; }
/** * 長(zhǎng)按多選,添加了選擇模式 * @description: * @author ldm * @date 2016-4-21 上午10:47:55 */ public class ChoiceModeList extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); lv.setMultiChoiceModeListener(new ModeCallback()); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, mStrings)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActionBar().setSubtitle("Long press to start selection"); } private class ModeCallback implements ListView.MultiChoiceModeListener { public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_select_menu, menu); mode.setTitle("Select Items"); setSubtitle(mode); return true; } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.share: Toast.makeText(ChoiceModeList.this, "Shared " + getListView().getCheckedItemCount() + " items", Toast.LENGTH_SHORT).show(); mode.finish(); break; default: Toast.makeText(ChoiceModeList.this, "Clicked " + item.getTitle(), Toast.LENGTH_SHORT).show(); break; } return true; } public void onDestroyActionMode(ActionMode mode) { } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { setSubtitle(mode); } private void setSubtitle(ActionMode mode) { final int checkedCount = getListView().getCheckedItemCount(); switch (checkedCount) { case 0: mode.setSubtitle(null); break; case 1: mode.setSubtitle("One item selected"); break; default: mode.setSubtitle("" + checkedCount + " items selected"); break; } } } private String[] mStrings = Cheeses.sCheeseStrings; }
當(dāng)我們通過以上這些方法實(shí)現(xiàn)ListView選中之后,我們可以把對(duì)應(yīng)的item位置記錄下來,就可以對(duì)相應(yīng)地?cái)?shù)據(jù)進(jìn)行操作了
/** * 帶懸浮提示框的ListView * * @description: * @author ldm * @date 2016-4-21 上午10:55:51 */ public class List9 extends ListActivity implements ListView.OnScrollListener { private final class RemoveWindow implements Runnable { public void run() { removeWindow(); } } private RemoveWindow mRemoveWindow = new RemoveWindow(); Handler mHandler = new Handler(); private WindowManager mWindowManager; private TextView mDialogText; private boolean mShowing; private boolean mReady; private char mPrevLetter = Character.MIN_VALUE; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); getListView().setOnScrollListener(this); LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); mDialogText = (TextView) inflate.inflate(R.layout.list_position, null); mDialogText.setVisibility(View.INVISIBLE); mHandler.post(new Runnable() { public void run() { mReady = true; WindowManager.LayoutParams lp = new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); mWindowManager.addView(mDialogText, lp); } }); } @Override protected void onResume() { super.onResume(); mReady = true; } @Override protected void onPause() { super.onPause(); removeWindow(); mReady = false; } @Override protected void onDestroy() { super.onDestroy(); mWindowManager.removeView(mDialogText); mReady = false; } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mReady) { char firstLetter = mStrings[firstVisibleItem].charAt(0); if (!mShowing && firstLetter != mPrevLetter) { mShowing = true; mDialogText.setVisibility(View.VISIBLE); } mDialogText.setText(((Character) firstLetter).toString()); mHandler.removeCallbacks(mRemoveWindow); mHandler.postDelayed(mRemoveWindow, 3000); mPrevLetter = firstLetter; } } public void onScrollStateChanged(AbsListView view, int scrollState) { } private void removeWindow() { if (mShowing) { mShowing = false; mDialogText.setVisibility(View.INVISIBLE); } } private String[] mStrings = new String[] { "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", "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", "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", "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", "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", "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", "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", "Venaco", "Vendomois", "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue", "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington", "Wensleydale", "White Stilton", "Zanetti Parmigiano Reggiano" }; }
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android控件用法總結(jié)》、《Android開發(fā)入門與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android數(shù)據(jù)庫操作技巧總結(jié)》及《Android資源操作技巧匯總》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android實(shí)現(xiàn)彈出列表、單選、多選框
- Android ExpandableListView單選以及多選實(shí)現(xiàn)代碼
- Android自定義單選多選下拉列表的實(shí)例代碼
- Android Recyclerview實(shí)現(xiàn)多選,單選,全選,反選,批量刪除的功能
- Android使用AlertDialog實(shí)現(xiàn)的信息列表單選、多選對(duì)話框功能
- Android中ListView + CheckBox實(shí)現(xiàn)單選、多選效果
- Android實(shí)現(xiàn)單選與多選對(duì)話框的代碼
- Android ListView構(gòu)建支持單選和多選的投票項(xiàng)目
- Android中創(chuàng)建對(duì)話框(確定取消對(duì)話框、單選對(duì)話框、多選對(duì)話框)實(shí)例代碼
- Android單選多選按鈕的使用方法
相關(guān)文章
Android DatePicker和DatePickerDialog基本用法示例
這篇文章主要介紹了Android DatePicker和DatePickerDialog基本用法,實(shí)例分析了DatePicker和DatePickerDialog控件針對(duì)手機(jī)時(shí)間設(shè)置的相關(guān)技巧,需要的朋友可以參考下2016-06-06kotlin中object關(guān)鍵字的三種使用場(chǎng)景
這篇文章主要給大家介紹了關(guān)于kotlin中object關(guān)鍵字的三種使用場(chǎng)景,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用kotlin具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06Android自定義View圖片按Path運(yùn)動(dòng)和旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Android自定義View圖片按Path運(yùn)動(dòng)和旋轉(zhuǎn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Android實(shí)現(xiàn)中國(guó)象棋游戲(局域網(wǎng)版)
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)局域網(wǎng)版的中國(guó)象棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05android實(shí)現(xiàn)靜默安裝與卸載的方法
這篇文章主要介紹了android實(shí)現(xiàn)靜默安裝與卸載的方法,涉及Android權(quán)限與命令行操作的相關(guān)技巧,需要的朋友可以參考下2015-05-05Android中使用的定時(shí)針(刷新頁面請(qǐng)求服務(wù)器)詳解
這篇文章主要介紹了Android中使用的定時(shí)針(刷新頁面請(qǐng)求服務(wù)器)詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12android 傳感器(OnSensorChanged)使用介紹
當(dāng)傳感器的值發(fā)生變化時(shí),例如磁阻傳感器方向改變時(shí)會(huì)調(diào)用OnSensorChanged(). 當(dāng)傳感器的精度發(fā)生變化時(shí)會(huì)調(diào)用OnAccuracyChanged()方法2014-11-11Android仿新浪微博自定義ListView下拉刷新(4)
這篇文章主要為大家詳細(xì)介紹了Android仿新浪微博自定義ListView下拉刷新,重點(diǎn)介紹了Adapter的詳細(xì)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11Android Studio 4.1沒有GsonFormat插件的解決
這篇文章主要介紹了Android Studio 4.1沒有GsonFormat插件的解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11