Android:自定义View实现多种滑动条

Android自定义View的滑动条实现
摘要由CSDN通过智能技术生成

话不多说 上效果图

       其实这两种本质上都是一样的,只是水平和竖直的区别,我也是借鉴了别的大佬的代码写的,原文章是刻度尺的,原文地址:(353条消息) 自定义view之刻度尺_拍码屁的博客-CSDN博客

第一步呢,也是跟原文章一样的步骤,定义好View的属性,在values文件夹下面创建一个attrs.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Ruler">
        <attr name="interval" format="dimension"/>
        <attr name="fromValue" format="integer"/>
        <attr name="toValue" format="integer"/>
        <attr name="currentValue" format="integer"/>
        <attr name="intervalsBetweenValues" format="integer"/>
        <attr name="valuesInterval" format="integer"/>
        <attr name="valuesTextSize" format="dimension"/>
        <attr name="valuesTextColor" format="color"/>
        <attr name="linesWidth" format="dimension"/>
        <attr name="linesColor" format="color"/>
        <attr name="isShowPointer" format="boolean"/>
        <attr name="orientation">
            <enum name="vertical" value="0"/>
            <enum name="horizontal" value="1"/>
        </attr>
    </declare-styleable>
</resources>

 第二步呢,就是开始写我们的自定义View啦:

水平的自定义View的Java文件如下:


/**
 * Created by Eve on 2022/9/30.
 */
public class RulerView extends View {

    //两刻度之间的距离
    private int interval;
    //起始值
    private int fromValue = 0;
    //结束值
    private int toValue = 300;
    //两刻度之间的单位
    private int intervalsBetweenValues = 1;
    //两刻度的差值
    private int valuesInterval = 1;
    //当前值
    private int currentValue;
    private Paint paint;
    private int currentPosition;
    private int offset;
    private int oldX;

    private OnMoveActionListener mMove = null;


    public RulerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.Ruler);
        interval=array.getDimensionPixelSize(R.styleable.Ruler_interval, dp2px(intervalsBetweenValues));
        currentValue=array.getInt(R.styleable.Ruler_currentValue, (fromValue+toValue)/2);
        array.recycle();
        paint=new Paint();
        //当前所指的刻度位置,即指示针指向的值
        currentPosition=currentValue/valuesInterval*intervalsBetweenValues;
    }


    public RulerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    }

    public static int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().get
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值