Letter index query listview component

Source: Internet
Author: User
Tags gety

Now many Android applications have implemented the letter index query function similar to iOS. Today I have encapsulated this function into a component.

Screen when you click or move it up or down a letter

Package COM. alphabet. widget; import android. content. context; import android. graphics. color; import android. OS. handler; import android. util. attributeset; import android. view. gravity; import android. view. motionevent; import android. view. view; import android. view. viewgroup; import android. widget. framelayout; import android. widget. linearlayout; import android. widget. listadapter; import android. widget. listview; impo RT android. widget. textview;/*** listview with letters on the right * @ author davee */public class alphabetlistview extends framelayout {private context mcontext; private listview mlistview; private linearlayout alphabetlayout; private textview mtextview; private alphabetpositionlistener positionlistener; private float screendensity; private handler mhandler; private hideindicator mhideindicator = new hideindicat Or (); Private int indicatorduration = 1000; Public void setindicatorduration (INT duration) {This. indicatorduration = duration;} private final class hideindicator implements runnable {@ override public void run () {mtextview. setvisibility (view. invisible) ;}} public alphabetlistview (context) {super (context); Init (context);} public alphabetlistview (context, attributeset attrs ){ Super (context, attrs); Init (context);} private void Init (context) {mcontext = context; screendensity = context. getresources (). getdisplaymetrics (). density; mhandler = new handler (); mlistview = new listview (mcontext); initalphabetlayout (mcontext); mtextview = new textview (mcontext); mtextview. settextsize (convertdip2px (50); mtextview. settextcolor (color. argb (150,255,255,255); mtextview. Setbackgroundcolor (color. argb (200, 0, 0, 0); mtextview. setminwidth (convertdip2px (70); mtextview. setminheight (convertdip2px (70); int pixels = convertdip2px (10); mtextview. setpadding (pixels, pixels); mtextview. setgravity (gravity. center); mtextview. setvisibility (view. invisible); framelayout. layoutparams textlayoutparams = new framelayout. layoutparams (viewgroup. layoutparams. wrap_c Ontent, viewgroup. layoutparams. wrap_content); textlayoutparams. gravity = gravity. center; // textlayoutparams. rightmargin = convertdip2px (10); mtextview. setlayoutparams (textlayoutparams);} public void setadapter (listadapter adapter, alphabetpositionlistener positionlistener) {If (positionlistener = NULL) throw new listener ("alphabetpositionlistener is required"); mlistview. setadap Ter (adapter); this. positionlistener = positionlistener; this. addview (mlistview); this. addview (alphabetlayout); this. addview (mtextview);} private void initalphabetlayout (context) {// create a letter layout alphabetlayout = new linearlayout (context); alphabetlayout. setorientation (linearlayout. vertical); framelayout. layoutparams alphabetlayoutparams = new framelayout. layoutparams (convertdip2px (30), viewgro Up. layoutparams. fill_parent); alphabetlayoutparams. gravity = gravity. right | gravity. center_vertical; alphabetlayoutparams. rightmargin = convertdip2px (10); alphabetlayout. setlayoutparams (alphabetlayoutparams); final string [] alphabet = new string [] {"A", "B", "C", "D", "E", "F ", "G", "H", "I", "J", "k", "L", "M", "n", "O", "P ", "Q", "L", "S", "T", "U", "V", "W", "X", "Y ", "Z"}; linearlayout. layoutparams Params = new linearl Ayout. layoutparams (linearlayout. layoutparams. wrap_content, linearlayout. layoutparams. wrap_content); Params. weight = 1; Params. gravity = gravity. center_horizontal; For (INT I = 0, Count = alphabet. length; I <count; I ++) {textview = new textview (context); textview. settextcolor (color. argb (150,150,150,150); textview. settextsize (convertdip2px (10); textview. settext (alphabet [I]); textview. se Tgravity (gravity. center); textview. setlayoutparams (Params); textview. settag (I + 1); alphabetlayout. addview (textview);} alphabetlayout. setontouchlistener (New ontouchlistener () {@ override public Boolean ontouch (view V, motionevent event) {Switch (event. getaction () {Case motionevent. action_down: alphabetlayout. setbackgroundcolor (color. argb (50,100,200,100); int L = (INT) (event. gety ()/(alphabetla Yout. getheight ()/26); If (L> 25) L = 25; else if (L <0) L = 0; int Pos = positionlistener. getposition (alphabet [l]); If (Pos! =-1) {mtextview. settext (alphabet [l]); mtextview. setvisibility (view. visible); mhandler. removecallbacks (mhideindicator); mhandler. postdelayed (mhideindicator, indicatorduration); // mlistview. requestfocusfromtouch (); mlistview. setselection (POS);} break; Case motionevent. action_move: L = (INT) (event. gety () + alphabetlayout. getheight ()/26/2)/(alphabetlayout. getheight ()/26); If (L> 25) L = 25; else if (L <0) L = 0; Pos = positionlistener. getposition (alphabet [l]); If (Pos! =-1) {mtextview. settext (alphabet [l]); mtextview. setvisibility (view. visible); mhandler. removecallbacks (mhideindicator); mhandler. postdelayed (mhideindicator, indicatorduration); // mlistview. requestfocusfromtouch (); mlistview. setselection (POS);} break; Case motionevent. action_up: alphabetlayout. setbackgroundresource (0); break;} return true ;}});} public int convertdip2px (float DIP) {return (int) (Dip * screendensity + 0.5f * (DIP> = 0? 1:-1);} public static interface alphabetpositionlistener {public static final int unknow =-1; Public int getposition (string letter );}}

Example

<?xml version="1.0" encoding="utf-8"?><com.alphabet.widget.AlphabetListView    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/list_view"    android:layout_width="fill_parent"    android:layout_height="fill_parent"/>

package com.alphabet;import com.alphabet.widget.AlphabetListView;import com.alphabet.widget.AlphabetListView.AlphabetPositionListener;import android.app.Activity;import android.os.Bundle;import android.widget.ArrayAdapter;public class AlphabetListViewActivity extends Activity {    private AlphabetListView alphabetListView;        private String[] mStrings = {            "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",            "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",            "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase",            "Button (Innes)", "Buxton Blue", "Cabecou", "Caboc", "Cabrales",            "Cachaille", "Caciocavallo", "Caciotta", "Caerphilly",            "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",            "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",            "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",            "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",            "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"};    private AlphabetPositionListener positionListener = new AlphabetPositionListener() {        @Override        public int getPosition(String letter) {            for(int i=0, count=mStrings.length; i<count; i++){                Character firstLetter = mStrings[i].charAt(0);                if(firstLetter.toString().equals(letter)){                    return i;                }            }            return UNKNOW;        }    };    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.alphabet);                ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,                android.R.layout.simple_list_item_1, mStrings);        alphabetListView = (AlphabetListView)findViewById(R.id.list_view);        alphabetListView.setAdapter(mArrayAdapter, positionListener);    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.