`
445822357
  • 浏览: 731245 次
文章分类
社区版块
存档分类
最新评论

ListView 实现点击侧边A-Z快速查找

 
阅读更多



为了实现上面的A-Z 快速定位的功能

下面是main.xml的布局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llParent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/lvShow"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <TextView
        android:id="@+id/tvLetter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#BB000000"
        android:gravity="center"
        android:maxWidth="70dip"
        android:minWidth="70dip"
        android:padding="10dip"
        android:textColor="#99FFFFFF"
        android:textSize="50sp" >
    </TextView>

    <com.android.ianc.MyLetterView
        android:id="@+id/myView"
        android:layout_width="30dip"
        android:layout_height="fill_parent"
        android:layout_gravity="right" >
    </com.android.ianc.MyLetterView>

</FrameLayout>


其中定义了一个listView和定义了一个右侧边的View


下面是MyLetterView的code

package com.android.ianc;

import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyLetterView extends View {
	OnTouchingLetterChangedListener onTouchingLetterChangedListener;
	public static String[] b = { "#", "A", "B", "C", "D", "E", "F", "G", "H",
			"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
			"V", "W", "X", "Y", "Z" };
	int choose = -1;
	Paint paint = new Paint();

	public MyLetterView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public MyLetterView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyLetterView(Context context) {
		super(context);
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (showBkg) {
			canvas.drawColor(Color.parseColor("#40000000"));
		}

		int height = getHeight();
		int width = getWidth();
		int singleHeight = height / b.length;
		for (int i = 0; i < b.length; i++) {
			paint.setColor(Color.WHITE);
			paint.setTypeface(Typeface.DEFAULT_BOLD);
			paint.setAntiAlias(true);
			paint.setTextSize(20);
			if (i == choose) {
				paint.setColor(Color.parseColor("#3399ff"));
				paint.setFakeBoldText(true);
			}
			float xPos = width / 2 - paint.measureText(b[i]) / 2;
			float yPos = singleHeight * i + singleHeight;
			canvas.drawText(b[i], xPos, yPos, paint);
			paint.reset();
		}

	}

	private boolean showBkg = false;

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		final int action = event.getAction();
		final float y = event.getY();
		final int oldChoose = choose;
		final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
		final int c = (int) (y / getHeight() * b.length);

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			showBkg = true;
			if (oldChoose != c && listener != null) {
				if (c > 0 && c < b.length) {
					listener.onTouchingLetterChanged(b[c]);
					choose = c;
					invalidate();
				}
			}

			break;
		case MotionEvent.ACTION_MOVE:
			if (oldChoose != c && listener != null) {
				if (c > 0 && c < b.length) {
					listener.onTouchingLetterChanged(b[c]);
					choose = c;
					invalidate();
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			showBkg = false;
			choose = -1;
			invalidate();
			break;
		}
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
	}

	public void setOnTouchingLetterChangedListener(
			OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
		this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
	}

	public interface OnTouchingLetterChangedListener {
		public void onTouchingLetterChanged(String s);
	}

}

如上面所示主要是对A-Z进行布局,然后对Touch进行监听,滑动时候获取到当前的滑动的字母



下面是Activity的code

package com.android.ianc;

import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.ianc.MyLetterView.OnTouchingLetterChangedListener;

public class TestList extends Activity implements
		OnTouchingLetterChangedListener {

	private Window window;
	private TextView overlay;
	private ListView personList;
	private MyLetterView myView;
	private OverlayThread overlayThread = new OverlayThread();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		personList = (ListView) findViewById(R.id.lvShow);
		personList.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, sCheeseStrings));
		personList.setTextFilterEnabled(true);
		myView = (MyLetterView) findViewById(R.id.myView);

		myView.setOnTouchingLetterChangedListener(this);
		overlay = (TextView) findViewById(R.id.tvLetter);
		overlay.setVisibility(View.INVISIBLE);
	}

	public void onTouchingLetterChanged(String s) {
		// TODO Auto-generated method stub
		if (alphaIndexer(s) > 0) {
			int position = alphaIndexer(s);
			personList.setSelection(position);
			overlay.setText(s);
			overlay.setVisibility(View.VISIBLE);
			handler.removeCallbacks(overlayThread);
			handler.postDelayed(overlayThread, 1500);
		}
	}

	public static int alphaIndexer(String s) {
		int i = 0;
		for (; i < sCheeseStrings.length; i++) {
			if (sCheeseStrings[i].startsWith(s)) {
				break;
			}
		}
		return i;
	}

	private Handler handler = new Handler() {
	};

	private class OverlayThread implements Runnable {

		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	private String getAlpha(String str) {
		if (str == null) {
			return "#";
		}

		if (str.trim().length() == 0) {
			return "#";
		}

		char c = str.trim().substring(0, 1).charAt(0);
		Pattern pattern = Pattern.compile("^[A-Za-z]+{1}");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase();
		} else {
			return "#";
		}
	}

	public static final String[] sCheeseStrings = { "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" };

}




主要是当又测view滑动的时候list 进行 滑动的效果,以及show出当前的字母来




如果上面code还有什么问题,可以直接联系我哦!转载请保持下面链接

/**
*
* @author Star http://blog.csdn.net/wong_judy/article/details/7518220
*
*/




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics