欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义View26个字母索引

程序员文章站 2022-05-04 11:29:54
...
package com.example.zdyview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/*
* 王硕
* 2019.05.28
* 自定义view侧边栏
* */
public class MyView extends View {
    private int indext;
    private Paint paint;
    private char[] mCha=new char[26];
    private int mArea;
    private int left;
    private int right;

    public MyView(Context context) {
        this(context,null);

    }

    public MyView(Context context, AttributeSet attrs) {
        this(context, attrs,-1);

    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.RED);//设置颜色
        paint.setStrokeWidth(5);//设置画笔宽度
        paint.setAntiAlias(true);//抗锯齿
        paint.setTextSize(30);//设置写出的文字大小
        paint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int top=40;
        int down=getHeight()-40;
        right = getRight()-20;
        left = getWidth()-80;
        //上边的横线
        canvas.drawLine(left,top, right,top,paint);
        //左边的横线
        canvas.drawLine(left,top, left,down,paint);
        //下边的横线
        canvas.drawLine(left,down, right,down,paint);
        //右边的横线
        canvas.drawLine(right,top, right,down,paint);
        //获取画图的高度每个字母的高度

        int tot=down-top;

        mArea = tot/26;
        int stary=top+mArea/2;
        //写上文字
        for (int i = 0; i <mCha.length; i++) {

            mCha[i]= (char) +(i+'A');
            canvas.drawText( mCha[i]+"" , left +30,stary+mArea*i,paint);
        }

        paint.setTextSize(40);

        canvas.drawText(mCha[indext]+"",getWidth()/2,getHeight()/2,paint);

        }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        //获取你的点击的区域范围必须要在 矩形内
        if (x>=left && y>=20) {
            //获取下标,y-20是高度减去40然后在吧每一份的大小/一下获得点击的位置是哪里然后给下标赋值
            indext= (int) ((y-40)/mArea);
            Log.d("MyView", "indext:" + indext);
            //判断是否是超出了下标 如果超出了下标则非他设置成26
            if (indext>=mCha.length) {
                indext=mCha.length-1;
            }
            //刷新view

            invalidate();
            return  true;
        }
        return super.onTouchEvent(event);
    }
}

相关标签: view