文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android自定义字母选择侧边栏

2024-04-02 19:55

关注

本文实例为大家分享了Android自定义字母选择侧边栏的具体代码,供大家参考,具体内容如下

LetterSideBar.java


package com.zb.customview.widgets;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
 
import androidx.annotation.Nullable;
 
import com.zb.customview.R;
 
public class LetterSideBar extends View {
 
    private Paint mPaint;
    private int color, selectedColor;
    private float textSize, spacing;
    private String mChoosing = "Z";
    private OnLetterSelectedListener listener;
    private int width, height;
 
    private 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"};
 
    public interface OnLetterSelectedListener {
        //空表示取消选中
        void onSelected(String letter);
    }
 
    public void setOnLetterSelectedListener(OnLetterSelectedListener listener) {
        this.listener = listener;
    }
 
    public LetterSideBar(Context context) {
        this(context, null);
    }
 
    public LetterSideBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        if(null != attrs) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LetterSideBar);
            color = ta.getColor(R.styleable.LetterSideBar_LetterSideBar_textColor, Color.BLACK);
            selectedColor = ta.getColor(R.styleable.LetterSideBar_LetterSideBar_textSelectedColor, Color.RED);
            textSize = ta.getDimensionPixelSize(R.styleable.LetterSideBar_LetterSideBar_textSize, sp2px(12));
            spacing = ta.getDimensionPixelSize(R.styleable.LetterSideBar_LetterSideBar_spacing, dp2px(5));
            ta.recycle();
        }
        init();
    }
 
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(color);
        mPaint.setTextSize(textSize);
    }
 
    @Override
    protected void onDraw(Canvas canvas) {
        drawText(canvas);
        drawSelectedText(canvas, mChoosing);
    }
 
    private void drawText(Canvas canvas) {
        mPaint.setColor(color);
        for (int i=0; i<LETTERS.length; i++) {
            drawLetterAt(canvas, i, LETTERS[i]);
        }
    }
 
    private void drawSelectedText(Canvas canvas, String selected) {
        if(TextUtils.isEmpty(selected))
            return;
        mPaint.setColor(selectedColor);
        int position = -1;
        for(int i=0; i<LETTERS.length; i++) {
            if(selected.equals(LETTERS[i])) {
                position = i;
                break;
            }
        }
        if(position < 0 || position >= LETTERS.length)
            return;
        drawLetterAt(canvas, position, selected);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                if(isTouchInsideView(x, y)) {
                    //触摸在控件内
                    int position = caculatePosition(y);
                    if(position >= 0 && position < LETTERS.length) {
                        //合规位置
                        String letter = LETTERS[position];
                        if(!letter.equals(mChoosing)) { //与选中的不符 去刷新控件
                            mChoosing = letter;
                            performListener(mChoosing);
                            invalidate();
                        }
                    } else {
                        //不合规位置
                        if(null != mChoosing) {
                            mChoosing = null;
                            performListener(mChoosing);
                            invalidate();
                        }
                    }
                } else if(null != mChoosing) { //点击事件不在view内部
                    mChoosing = null;
                    performListener(mChoosing);
                    invalidate();//触摸在view之外 取消选中
                }
                return true;
            default:
                if(mChoosing != null) {
                    mChoosing = null;
                    performListener(mChoosing);
                    invalidate();
                }
                break;
        }
        return super.onTouchEvent(event);
    }
 
    private void performListener(String letter) {
        if(null != listener)
            listener.onSelected(letter);
    }
 
    private boolean isTouchInsideView(float x, float y) {
        //左右可以适当判断在控件内
        if(x >= 0 && x <= width && y >= getPaddingTop() && y < height)
            return true;
        return false;
    }
 
    
    private int caculatePosition(float y) {
        float heightWithOutPadding = height - getPaddingTop() - getPaddingBottom();
        float eachElementHeight = heightWithOutPadding / LETTERS.length;
        y -= getPaddingTop();
        int position = (int) (y / eachElementHeight);
        return position;
    }
 
    private void drawLetterAt(Canvas canvas, int position, String letter) {
 
        float heightForEach = ((height * 1f - getPaddingTop() - getPaddingBottom())
                - (LETTERS.length - 1) * spacing) / LETTERS.length;
        float spacingInUp = spacing * (position - 1);
        if(spacingInUp < 0)
            spacingInUp = 0;
        float currentTop = getPaddingTop() + (heightForEach * position) + spacingInUp;
        float currentBottom = currentTop + heightForEach;
        Paint.FontMetrics fmi = mPaint.getFontMetrics();
        float x = (width - getPaddingLeft() - getPaddingRight() - mPaint.measureText(letter)) / 2f + getPaddingLeft();
        float baseLine = (fmi.descent + Math.abs(fmi.ascent)) / 2f - fmi.descent;
        float y = (currentBottom + currentTop) / 2f + baseLine;
        canvas.drawText(letter, 0, 1, x, y, mPaint);
    }
 
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if(changed) {
            width = getWidth();
            height = getHeight();
        }
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int textWidth = (int) (getPaddingLeft() + getPaddingRight() + mPaint.measureText("A"));
        Rect textBounds = new Rect();
        mPaint.getTextBounds("A", 0, 1, textBounds);
        int singleTextHeight = textBounds.height();
        int totalHeight = (int) (27f * singleTextHeight + 26f * spacing) + getPaddingBottom() + getPaddingTop();//26个字母+1个#
 
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(widthMeasureSpec);
        int specWidth = MeasureSpec.getSize(widthMeasureSpec);
        int specHeight = MeasureSpec.getSize(widthMeasureSpec);
        int realWidth, realHeight;
        if(widthMode == MeasureSpec.EXACTLY) {
            realWidth = specWidth;
        } else {
            realWidth = textWidth;
        }
        if(heightMode == MeasureSpec.EXACTLY) {
            realHeight = specHeight;
        } else {
            realHeight = totalHeight;
        }
        setMeasuredDimension(realWidth, realHeight);
    }
 
    protected int dp2px(int dp) {
        return (int) (getContext().getResources().getDisplayMetrics().density * dp + 0.5);
    }
    protected int sp2px(int sp) {
        return (int) (getContext().getResources().getDisplayMetrics().scaledDensity * sp + 0.5);
    }
}

attrs.xml


<declare-styleable name="LetterSideBar"> 
<attr name="LetterSideBar_textColor" format="color"/> 
<attr name="LetterSideBar_textSelectedColor" format="color"/> 
<attr name="LetterSideBar_textSize" format="dimension"/> 
<attr name="LetterSideBar_spacing" format="dimension"/> 
</declare-styleable>

layout.xml


<com.zb.customview.widgets.LetterSideBar
        android:id="@+id/letterSideBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:LetterSideBar_textSize="14sp"
        app:LetterSideBar_textColor="#FFFFFF"
        android:padding="10dp"
        app:LetterSideBar_textSelectedColor="#FF0000"
        app:LetterSideBar_spacing="2dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="#A4A4A4"/>

代码中使用


sideBar.setOnLetterSelectedListener(new LetterSideBar.OnLetterSelectedListener() {
            @Override
            public void onSelected(String letter) {
                if(TextUtils.isEmpty(letter)) {
                    P.p("取消选中");
                    letterTxt.setVisibility(View.GONE);
                } else {
                    P.p("选中" + letter);
                    letterTxt.setText(letter);
                    letterTxt.setVisibility(View.VISIBLE);
                }
            }
        });

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯