在这次代码编写当中,我主要用到了WindowManager来显示友好提示
在对数组进行排序的时候,我们可以用 Arrays.sort()方法轻松实现按字母顺序排序。
另外在实现点击字母后让ListView滚动到以该字母开头的相应位置效果时,我们要用到如下方法:
一个是通过public static int binarySearch(Object[] a,Object key) 方法来获得该字母出现的Item在ListView中的位置position,
另一个就是 list.setSelection(localPosition); 来让List指向对应位置的Item。
当你对这些方法都有所了解了以后,下面我们开始设计我们的Demo。
我们先建立一个名为ContactsDemo的工程,然后就是代码部分了:
第一步,在res/layout的main.xml中我们来设置Activity中显示ListView上下层显示的效果,其实就是一个相对布局。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="@+id/listview"
android:layout_width="30dip"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:background="@null"
/>
</RelativeLayout>
第二步,我们在layout中建一个list_popup_char_hint.xml,这是用来通过WindowManager显示友好提示的。
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:textSize="70sp"
android:textColor="#ffffffff"
android:minWidth="70dip"
android:maxWidth="70dip"
android:padding="10dip"
android:gravity="center"
/>
第三步,是list_item.xml用来设置ListView中Items的布局。
<?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:id="@+id/text_first_char_hint"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dip"
android:paddingLeft="10dip"
android:background="@drawable/background"
android:visibility="gone">
</TextView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/order"
android:layout_width="wrap_content"
android:layout_height="60dip"
android:textSize="15dip"
android:layout_gravity="left"
android:layout_weight="2"/>
<TextView
android:id="@+id/content"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="60dip"
android:textSize="15dip"
android:layout_weight="2"/>
</LinearLayout >
</LinearLayout >
第四步,是一个textview.xml用来显示右边覆盖在ListView上的ListView的Items
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="20dip">
</TextView>
第五步,我们建一个名为ContactsDemo的类,然后就是实现功能的代码了,里面有非常详尽的注释,大家慢慢看吧。
package com.ContactsDemo;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
/**
* @author Mr.罗
*
*/
public class ContactsDemo extends Activity implements OnItemClickListener,OnScrollListener{
/** Called when the activity is first created. */
private MyListAdapter adapter;
private ArrayList<String> webNameArr;
private WindowManager windowManager;
private TextView txtOverlay; //用来放在WindowManager中显示提示字符
private Handler handler;
private DisapearThread disapearThread;
private int scrollState; //滚动的状态
private ListView list,listview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtOverlay = (TextView) LayoutInflater.from(this).inflate(R.layout.list_popup_char_hint, null);
// 默认设置为不可见。
txtOverlay.setVisibility(View.INVISIBLE);
//设置WindowManager
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION,
//设置为无焦点状态
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
//半透明效果
PixelFormat.TRANSLUCENT);
windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
windowManager.addView(txtOverlay, lp);
handler = new Handler();
disapearThread = new DisapearThread();
Arrays.sort(stringArr,String.CASE_INSENSITIVE_ORDER); //大小写不敏感
webNameArr = new ArrayList<String>();
for (int i = 0; i < stringArr.length; i++) {
webNameArr.add(stringArr[i]);
}
list = (ListView)this.findViewById(R.id.list); //联系人ListView
listview = (ListView)this.findViewById(R.id.listview); //拼音查询ListView
adapter = new MyListAdapter(this);
list.setAdapter(adapter);//将数据适配器与Activity进行绑定
list.setOnScrollListener(this);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,R.layout.textview,py);
listview.setAdapter(adapter1);
listview.setDivider(null);
listview.setOnItemClickListener(this);
}
private class DisapearThread implements Runnable {
public void run() {
// 避免在1.5s内,用户再次拖动时提示框又执行隐藏命令。
if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
txtOverlay.setVisibility(View.INVISIBLE);
}
}
}
//继承BaseAdapter来设置ListView每行的内容
public final class ViewHolder {
public TextView firstCharHintTextView;
public TextView orderTextView;
public TextView nameTextView;
public TextView urlTextView;
public ImageView imgView;
}
private class MyListAdapter extends BaseAdapter {
private LayoutInflater inflater;
public MyListAdapter(Context context) {
this.inflater = LayoutInflater.from(context);
}
public int getCount() {
return webNameArr.size();
}
public Object getItem(int position) {
return webNameArr.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.firstCharHintTextView = (TextView) convertView.findViewById(R.id.text_first_char_hint);
holder.orderTextView = (TextView) convertView.findViewById(R.id.order);
holder.nameTextView = (TextView) convertView.findViewById(R.id.content);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.orderTextView.setText(String.valueOf(position + 1) + ".");
holder.nameTextView.setText(webNameArr.get(position));
int idx = position - 1;
//判断前后Item是否匹配,如果不匹配则设置并显示,匹配则取消
char previewChar = idx >= 0 ? stringArr[idx].charAt(0) : ' ';
char currentChar = stringArr[position].charAt(0);
//将小写字符转换为大写字符
char newPreviewChar = Character.toUpperCase(previewChar);
char newCurrentChar = Character.toUpperCase(currentChar);
if (newCurrentChar != newPreviewChar) {
holder.firstCharHintTextView.setVisibility(View.VISIBLE);
holder.firstCharHintTextView.setText(String.valueOf(newCurrentChar));
} else {
// 此段代码不可缺:实例化一个CurrentView后,会被多次赋值并且只有最后一次赋值的position是正确
holder.firstCharHintTextView.setVisibility(View.GONE);
}
return convertView;
}
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// 以中间的ListItem为标准项来显示。
txtOverlay.setText(String.valueOf(stringArr[firstVisibleItem + (visibleItemCount >> 1)].charAt(0)).toUpperCase());
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.scrollState = scrollState;
if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
handler.removeCallbacks(disapearThread);
// 提示延迟1.5s再消失
handler.postDelayed(disapearThread, 1500);
} else {
txtOverlay.setVisibility(View.VISIBLE);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String s = ((TextView)view).getText().toString();
txtOverlay.setText(s);
txtOverlay.setVisibility(View.VISIBLE);
handler.removeCallbacks(disapearThread);
// 提示延迟1.5s再消失
handler.postDelayed(disapearThread, 1500);
int localPosition = binSearch(stringArr,s); //接收返回值
if(localPosition!=-1){
txtOverlay.setVisibility(View.INVISIBLE); //防止点击出现的txtOverlay与滚动出现的txtOverlay冲突
list.setSelection(localPosition); //让List指向对应位置的Item
}
}
//将选中的py与stringArr的首字符进行匹配并返回对应字符串在数组中的位置
public static int binSearch(String[] string , String s ){
for(int i=0;i<string.length;i++){
if(s.equalsIgnoreCase(""+string[i].charAt(0))){ //不区分大小写
return i;
}
}
return -1;
}
public void onDestroy() {
super.onDestroy();
// 将txtOverlay删除。
txtOverlay.setVisibility(View.INVISIBLE);
windowManager.removeView(txtOverlay);
}
/**在这里我们将字符串打乱,且含有大小写开头不等*/
private String[] stringArr = { "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",
"brebis du Lochois", "brebis du Puyfaucon", "aresse Bleu", "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", "eouyssou", "Bra", "Braudostur", "Breakfast Cheese", "Brebis du Lavort",
"Allgauer Emmentaler", "Alverca", "Ambert", "Brick", "Brie", "Brie de Meaux",
"Brie de Melun", "Brillat-Savarin", "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
"Briquette de Brebis", "driquette 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",
"Derby", "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "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", "frottin 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", "kalette 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 marmhouse", "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",
"Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "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"
};
private String py[]={"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"};
}
无图无真相,下面就是我运行的效果了: