Android自定义折线图,可左右滑动,可点击

本文详细介绍了如何在Android中自定义一个折线图,包括设置自定义属性,获取基本点,使用ondraw()方法绘制图表,并实现了左右滑动和点击事件的处理功能。提供了最终的效果图作为展示。

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

前言

       前几天有小盆友让我写一个折线图,可以点击,可以左右滑动。对于折线肯定有很多项目都使用过,所以网上肯定也有很多demo,像AndroidChart、HelloChart之类的,功能相当丰富,效果也很赞,但是太重了,其他的小demo又不符合要求,当然了,我写的自定义折线图的思想也有来自这些小demo,对他们表示感谢。

效果图

      废话不多说,先上效果图:


                                                            
     效果是不是很赞大笑,如果上图满足你的需求,那就继续往下看。

自定义折线图的步骤:

1、自定义view所需要的属性

确定所需要的自定义view的属性,然后在res/values目录下,新建一个attrs.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- xy坐标轴颜色 -->
    <attr name="xylinecolor" format="color" />
    <!-- xy坐标轴宽度 -->
    <attr name="xylinewidth" format="dimension" />
    <!-- xy坐标轴文字颜色 -->
    <attr name="xytextcolor" format="color" />
    <!-- xy坐标轴文字大小 -->
    <attr name="xytextsize" format="dimension" />
    <!-- 折线图中折线的颜色 -->
    <attr name="linecolor" format="color" />
    <!-- x轴各个坐标点水平间距 -->
    <attr name="interval" format="dimension" />
    <!-- 背景颜色 -->
    <attr name="bgcolor" format="color" />
    <!--是否在ACTION_UP时,根据速度进行自滑动,建议关闭,过于占用GPU-->
    <attr name="isScroll" format="boolean" />
    <declare-styleable name="chartView">
        <attr name="xylinecolor" />
        <attr name="xylinewidth" />
        <attr name="xytextcolor" />
        <attr name="xytextsize" />
        <attr name="linecolor" />
        <attr name="interval" />
        <attr name="bgcolor" />
        <attr name="isScroll" />
    </declare-styleable>
</resources>

2、在自定义view的构造方法中获取我们的自定义属性:

    public ChartView(Context context) {
        this(context, null);
    }

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

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

    /**
     * 初始化
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.chartView, defStyleAttr, 0);
        int count = array.getIndexCount();
        for (int i = 0; i < count; i++) {
            int attr = array.getIndex(i);
            switch (attr) {
                case R.styleable.chartView_xylinecolor://xy坐标轴颜色
                    xylineco
评论 38
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值