android自定义sidebar,Android仿微信通讯录列表侧边栏效果

本文介绍了如何在Android中实现类似微信通讯录的侧边栏索引效果,包括自定义SideBar视图,使用pinyin4j库解析汉字拼音,以及创建HintSideBar布局来显示居中提示文本。通过监听侧边栏触摸事件和回调接口,实现实时更新列表定位。详细步骤包括自定义View的绘制,用户数据的排序,以及适配器的使用。

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

先看Android仿微信通讯录列表侧边栏效果图

5292bbb21d3b4729563439bad49084fe.gif

这是比较常见的效果了吧

列表根据首字符的拼音字母来排序,且可以通过侧边栏的字母索引来进行定位。

实现这样一个效果并不难,只要自定义一个索引View,然后引入一个可以对汉字进行拼音解析的jar包——pinyin4j-2.5.0即可

首先,先来定义侧边栏控件View,只要直接画出来即可。

字母选中项会变为红色,且滑动时背景会变色,此时SideBar并不包含居中的提示文本

public class SideBar extends View {

private Paint paint = new Paint();

private int choose = -1;

private boolean showBackground;

public static String[] letters = {"#", "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 OnChooseLetterChangedListener onChooseLetterChangedListener;

public SideBar(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

public SideBar(Context context, AttributeSet attrs) {

super(context, attrs);

}

public SideBar(Context context) {

super(context);

}

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

if (showBackground) {

canvas.drawColor(Color.parseColor("#D9D9D9"));

}

int height = getHeight();

int width = getWidth();

//平均每个字母占的高度

int singleHeight = height / letters.length;

for (int i = 0; i < letters.length; i++) {

paint.setColor(Color.BLACK);

paint.setAntiAlias(true);

paint.setTextSize(25);

if (i == choose) {

paint.setColor(Color.parseColor("#FF2828"));

paint.setFakeBoldText(true);

}

float x = width / 2 - paint.measureText(letters[i]) / 2;

float y = singleHeight * i + singleHeight;

canvas.drawText(letters[i], x, y, paint);

paint.reset();

}

}

@Override

public boolean dispatchTouchEvent(MotionEvent event) {

int action = event.getAction();

float y = event.getY();

int oldChoose = choose;

int c = (int) (y / getHeight() * letters.length);

switch (action) {

case MotionEvent.ACTION_DOWN:

showBackground = true;

if (oldChoose != c && onChooseLetterChangedListener != null) {

if (c > -1 && c < letters.length) {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值