8.快速索引、listview
实现这样的效果
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<com.itheima.quickindex.ui.QuickIndexBar
android:id="@+id/bar"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#ff0000" />
<TextView
android:id="@+id/tv_center"
android:layout_width="160dp"
android:layout_height="100dp"
android:background="@drawable/bg_index"
android:gravity="center"
android:textSize="32sp"
android:visibility="gone"
android:textColor="#ffffff"
android:layout_centerInParent="true"
android:text="A" />
</RelativeLayout>
字的shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#66000000"/>
<corners android:radius="20dp"/>
</shape>
QuickIndexBar
/**
* 快速索引
*
* 用于根据字母快速定位联系人
* @author poplar
*
*/
public class QuickIndexBar extends View {
private static final String[] LETTERS = new String[]{
"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"};
private static final String TAG = "TAG";
private Paint mPaint;
private int cellWidth;
private float cellHeight;
/**
* 暴露一个字母的监听,交给main执行
*/
public interface OnLetterUpdateListener{
void onLetterUpdate(String letter);
}
private OnLetterUpdateListener listener;
public OnLetterUpdateListener getListener() {
return listener;
}
/**
* 设置字母更新监听
* @param listener
*/
public void setListener(OnLetterUpdateListener listener) {
this.listener = listener;
}
public QuickIndexBar(Context context) {
this(context, null);
}
public QuickIndexBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);//这样写,只需要在三个参数的构造函数初始化就可以了
}
public QuickIndexBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.WHITE);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);//当点中的时候变粗
}
@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < LETTERS.length; i++) {
String text = LETTERS[i];
// 计算坐标
int x = (int) (cellWidth / 2.0f - mPaint.measureText(text) / 2.0f);//先转成float再转成int,因为有可能丢失精度
// 获取文本的高度
Rect bounds = new Rect();// 矩形
mPaint.getTextBounds(text, 0, text.length(), bounds);//字是矩形,通过矩形获得高
int textHeight = bounds.height();
int y = (int) (cellHeight / 2.0f + textHeight / 2.0f + i * cellHeight);
// 根据按下的字母, 设置画笔颜色
mPaint.setColor(touchIndex == i ? Color.GRAY : Color.WHITE);
// 绘制文本A-Z
canvas.drawText(text, x, y, mPaint);
}
}
int touchIndex = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
int index = -1;
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
// 获取当前触摸到的字母索引
index = (int) (event.getY() / cellHeight);
if(index >= 0 && index < LETTERS.length){
// 判断是否跟上一次触摸到的一样
if(index != touchIndex) {
if(listener != null){
listener.onLetterUpdate(LETTERS[index]);
}
Log.d(TAG, "onTouchEvent: " + LETTERS[index]);
touchIndex = index;
}
}
break;
case MotionEvent.ACTION_MOVE:
index = (int) (event.getY() / cellHeight);
if(index >= 0 && index < LETTERS.length){
// 判断是否跟上一次触摸到的一样
if(index != touchIndex){
if(listener != null){
listener.onLetterUpdate(LETTERS[index]);
}
Log.d(TAG, "onTouchEvent: " + LETTERS[index]);
touchIndex = index;
}
}
break;
case MotionEvent.ACTION_UP:
touchIndex = -1;
break;
default:
break;
}
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 获取单元格的宽和高
cellWidth = getMeasuredWidth();
int mHeight = getMeasuredHeight();
cellHeight = mHeight * 1.0f / LETTERS.length;
}
}
public class PinyinUtils {
/**
* 根据传入的字符串(包含汉字),得到拼音
* 黑马 -> HEIMA
* 黑 马*& -> HEIMA
* 黑马f5 -> HEIMA
* @param str 字符串
* @return
*/
public static String getPinyin(String str) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
StringBuilder sb = new StringBuilder();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
// 如果是空格, 跳过
if(Character.isWhitespace(c)){
continue;
}
if(c >= -127 && c < 128){
// 肯定不是汉字
sb.append(c);
}else {
String s = "";
try {
// 通过char得到拼音集合. 单 -> dan, shan
s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
sb.append(s);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
sb.append(s);
}
}
}
return sb.toString();
}
}
Person
public class Person implements Comparable<Person>{//实现比较功能
private String name;
private String pinyin;
public Person(String name) {
super();
this.name = name;
this.pinyin = PinyinUtils.getPinyin(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
@Override
public int compareTo(Person another) {
return this.pinyin.compareTo(another.getPinyin());
}
}
adapter布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_index"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#888888"
android:gravity="center_vertical"
android:paddingLeft="20dp"
android:text="A"
android:textColor="#ffffff"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:paddingLeft="20dp"
android:text="宋江"
android:textSize="24sp" />
</LinearLayout>
HaoHanAdapter
public class HaoHanAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Person> persons;
public HaoHanAdapter(Context mContext, ArrayList<Person> persons) {
this.mContext = mContext;
this.persons = persons;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return persons.size();
}
@Override
public Object getItem(int position) {
return persons.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null){
view = view.inflate(mContext, R.layout.item_list, null);
}
ViewHolder mViewHolder = ViewHolder.getHolder(view);
Person p = persons.get(position);
String str = null;
String currentLetter = p.getPinyin().charAt(0) + "";
// 根据上一个首字母,决定当前是否显示字母
if(position == 0){
str = currentLetter;
}else {
// 上一个人的拼音的首字母
String preLetter = persons.get(position - 1).getPinyin().charAt(0) + "";
if(!TextUtils.equals(preLetter, currentLetter)){
str = currentLetter;
}
}
// 根据str是否为空,决定是否显示索引栏
mViewHolder.mIndex.setVisibility(str == null ? View.GONE : View.VISIBLE);
mViewHolder.mIndex.setText(currentLetter);
mViewHolder.mName.setText(p.getName());
return view;
}
static class ViewHolder {
TextView mIndex;
TextView mName;
public static ViewHolder getHolder(View view) {//了解这种写法
Object tag = view.getTag();
if(tag != null){
return (ViewHolder)tag;
}else {
ViewHolder viewHolder = new ViewHolder();
viewHolder.mIndex = (TextView) view.findViewById(R.id.tv_index);
viewHolder.mName = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
return viewHolder;
}
}
}
}
MainActivity
public class MainActivity extends Activity {
private ListView mMainList;
private ArrayList<Person> persons;
private TextView tv_center;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuickIndexBar bar = (QuickIndexBar) findViewById(R.id.bar);
// 设置监听,和回调一个意思
bar.setListener(new OnLetterUpdateListener() {
@Override
public void onLetterUpdate(String letter) {
// Utils.showToast(getApplicationContext(), letter);
showLetter(letter);
// 根据字母定位ListView, 找到集合中第一个以letter为拼音首字母的对象,得到索引
for (int i = 0; i < persons.size(); i++) {
Person person = persons.get(i);
String l = person.getPinyin().charAt(0) + "";
if(TextUtils.equals(letter, l)){
// 匹配成功
mMainList.setSelection(i);
break;
}
}
}
});
mMainList = (ListView) findViewById(R.id.lv_main);
persons = new ArrayList<Person>();
// 填充数据 , 排序
fillAndSortData(persons);
mMainList.setAdapter(new HaoHanAdapter(MainActivity.this , persons));
tv_center = (TextView) findViewById(R.id.tv_center);
}
private Handler mHandler = new Handler();
/**
* 显示字母
* @param letter
*/
protected void showLetter(String letter) {
tv_center.setVisibility(View.VISIBLE);
tv_center.setText(letter);
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
tv_center.setVisibility(View.GONE);
}
}, 2000);
}
private void fillAndSortData(ArrayList<Person> persons) {
// 填充数据
for (int i = 0; i < Cheeses.NAMES.length; i++) {
String name = Cheeses.NAMES[i];
persons.add(new Person(name));
}
// 进行排序
Collections.sort(persons);
}
}
附件列表