专栏首页Android开发指南8.快速索引、listview

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;
 }
}

PinyinUtils

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);
 }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 10.下拉刷新、加载更多、标记已读、轮播条、缓存

    六月的雨
  • 16.语音识别

    六月的雨
  • 1.viewpager

    六月的雨
  • 读取联系人

    Dream城堡
  • PinnedSectionListView详细介绍(android开源项目)

    我在之前的博客http://blog.csdn.net/lxj1137800599/article/details/51752970 介绍过PinnedSect...

    提莫队长
  • 移动架构-IOC架构设计

    控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖...

    Android技术干货分享
  • 笔记73 | 实现音乐转盘的旋转和暂停效果

    项勇
  • Android PowerImageView实现,可以播放动画的强大ImageView

    我个人是比较喜欢逛贴吧的,贴吧里总是会有很多搞笑的动态图片,经常看一看就会感觉欢乐很多,可以释放掉不少平时的压力。确实,比起一张单调的图片,动态图片明显更加的有...

    用户1158055
  • Cordova@6.4.0以上灵活修改配置

    还记得我在此文【技巧】ionic3优雅解决启动前、后黑白屏问题中添加了一个勾子插件cordova-custom-config来修改配置的主题。

    IT晴天
  • Android实现轮播图点击图片放大效果

    最近项目中需要实现轮播图显示商品图片,当用户点击商品图片的时候,需要图片放大显示,当然用户还能进行多张图片的滑动切换,放大,缩小图片等操作,实现起来相对还是比较...

    SoullessCoder

扫码关注云+社区

领取腾讯云代金券