①最右侧的索引是用自定义View来实现的,通过onDraw方法将其描绘;②用pinyin4j-2.5.0.jar第三方架包取到每个名字的首字母,将汉字转化成拼音再取第一个字符;③ListView的adapte适配器。如下图所示:
1 布局实现
单个记录的实现,代码如下:
item_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#44000000"
android:text="A"
android:textColor="#000000"
android:textSize="25sp" />
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="阿三"
android:textColor="#000000"
android:textSize="25sp" />
</LinearLayout>
主页面布局的实现,代码如下
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.atguigu.quickindex.MainActivity">
<!--左边内容-->
<ListView
android:id="@+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--中间内容-->
<TextView
android:id="@+id/tv_word"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerInParent="true"
android:background="#44000000"
android:gravity="center"
android:text="A"
android:textColor="#000000"
android:textSize="30sp"
android:visibility="gone" />
<!--右边内容-->
<com.wang.quickindex.IndexView
android:id="@+id/iv_words"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#ff0000" />
</RelativeLayout>
2 代码功能实现
自定义的View来实现快速索引,代码如下:
/**
* 作用:快速索引,绘制26个字母
* 1.把26个字母放入数组
* 2.在onMeasure计算每条的高itemHeight和宽itemWidth,
* 3.在onDraw和wordWidth,wordHeight,wordX,wordY
*
* 手指按下文字变色
* 1.重写onTouchEvent(),返回true,在down/move的过程中计算
* int touchIndex = Y / itemHeight; 强制绘制
*
* 2.在onDraw()方法对于的下标设置画笔变色
*
* 3.在up的时候
* touchIndex = -1; //还原默认
* 强制绘制
*/
pu