Android自定义View实现快速索引(如微信好友列表,通讯录)

本文详细介绍了如何在Android中实现类似微信好友列表的快速索引功能。通过自定义View绘制索引,利用pinyin4j库获取汉字首字母,并在ListView的Adapter中进行适配,实现高效的一键跳转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

①最右侧的索引是用自定义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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值