Android-打造酷炫进度条

1.为什么要自定义控件

  • 特定的显示风格
  • 处理特有的用户交互
  • 优化我们的布局
  • 封装等

2. 如何自定义控件

  1. 自定义属性的声明与获取
  2. 测量onMeasure
  3. 布局onLayout(ViewGroup)
  4. 绘制onDraw
  5. onTouchEvent
  6. onInterceptTouchEvent(ViewGroup)
  7. 状态的恢复与保存

2.1 自定义属性声明与获取

  1. 分析需要的自定义属性
    进度条未到达部分的颜色、高度,进度条到达部分的颜色、高度,字体颜色、大小、偏移量
  2. 在res/values/attrs.xml定义声明
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="progress_unreach_color" format="color"/>
    <attr name="progress_unreach_height" format="dimension"/>
    <attr name="progress_reach_color" format="color"/>
    <attr name="progress_reach_height" format="dimension"/>
    <attr name="progress_text_color" format="color"/>
    <attr name="progress_text_size" format="dimension"/>
    <attr name="progress_text_offset" format="dimension"/>
    
    <declare-styleable name="HorizontalProgressbarWithProgress">
        <attr name="progress_unreach_color"/>
        <attr name="progress_unreach_height"/>
        <attr name="progress_reach_color"/>
        <attr name="progress_reach_height"/>
        <attr name="progress_text_color"/>
        <attr name="progress_text_size"/>
        <attr name="progress_text_offset"/> 
    </declare-styleable>
</resources>
  1. 在layout文件中进行声明
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.example.progressbar.view.HorizontalProgressbarWithProgress
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="50"
            android:padding="5dp"
            android:layout_marginTop="30dp"/>

        <com.example.progressbar.view.HorizontalProgressbarWithProgress
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="50"
            android:padding="5dp"
            app:progress_text_color="#44fc00"
            app:progress_unreach_color="#ff0000"
            android:layout_marginTop="30dp"/>
        <com.example.progressbar.view.HorizontalProgressbarWithProgress
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="50"
            android:padding="5dp"
            app:progress_text_color="#44ff00"
            app:progress_unreach_color="#ff00"
            android:layout_marginTop="30dp"/>

    </LinearLayout>

</ScrollView>
  1. 在View的构造方法中进行获取
package com.example.progressbar.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

import com.example.progressbar.R;

import java.lang.reflect.Type;

public class HorizontalProgressbarWithProgress extends ProgressBar {
    private static final int DEFAULT_TEXT_SIZE = 10; // sp
    private static final int DEFAULT_TEXT_COLOR = 0xFFC00D1;
    private static final int DEFAULT_COLOR_UNREACH = 0xFFD3D6DA;
    private static final int DEFAULT_HEIGHT_UNREACH = 2; // dp
    private static final int DEFAULT_COLOR_REACH = 0xFFC00D1;
    private static final int DEFAULT_HEIGHT_REACH = 2; // dp
    private static final int DEFAULT_TEXT_OFFSET = 10; // dp

    private int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
    private int mTextColor = DEFAULT_TEXT_COLOR;
    private int mUnReachColor = DEFAULT_COLOR_UNREACH;
    private int mUnReachHeight = dp2px(DEFAULT_HEIGHT_UNREACH);
    private int mReachColor = DEFAULT_COLOR_REACH;
    private int mReachHeight = dp2px(DEFAULT_HEIGHT_REACH);
    private int mTextOffset = dp2px(DEFAULT_TEXT_OFFSET);

    private Paint mPaint = new Paint();

    private int mRealWidth;

    public HorizontalProgressbarWithProgress(Context context) {
        super(context, null, 0);
    }

    public HorizontalProgressbarWithProgress(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public HorizontalProgressbarWithProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        obtainStyledAttrs(attrs);
    }

    /**
     * 获取自定义属性
     * @param attrs
     */
    private void obtainStyledAttrs(AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalProgressbarWithProgress);
        mTextSize = (int) ta.getDimension(R.styleable.HorizontalProgressbarWithProgress_progress_text_size, mTextSize);
        mTextColor = ta.getColor(R.styleable.HorizontalProgressbarWithProgress_progress_text_color, mTextColor);
        mTextOffset = (int) ta.getDimension(R.styleable.HorizontalProgressbarWithProgress_progress_text_offset, mTextOffset);
        mUnReachColor = ta.getColor(R.styleable.HorizontalProgressbarWithProgress_progress_text_color, mUnReachColor);
        mUnReachHeight = (int) ta.getDimension(R.styleable.HorizontalProgressbarWithProgress_progress_unreach_height, mUnReachHeight);
        mReachColor = ta.getColor(R.styleable.HorizontalProgressbarWithProgress_progress_reach_color, mReachColor);
        mReachHeight = (int) ta.getDimension(R.styleable.HorizontalProgressbarWithProgress_progress_reach_height, mReachHeight);
        ta.recycle();

        mPaint.setTextSize(mTextSize);
    }

//    重写测量方法
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthVal = MeasureSpec.getSize(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(widthVal, height);
//        实际绘制的宽度
        mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
    }

//    测量高度
    private int measureHeight(int heightMeasureSpec) {
        int res = 0;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);
        if (mode == MeasureSpec.EXACTLY) {
            res = size;
        } else {
            int textHeight = (int) (mPaint.descent() - mPaint.ascent());
            res = getPaddingTop() + getPaddingBottom() +
                    Math.max(Math.max(mReachHeight, mUnReachHeight), Math.abs(textHeight));
            if (mode == MeasureSpec.AT_MOST) {
                res = Math.min(res, size);
            }
        }
        return res;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getPaddingLeft(), getHeight() / 2);
        float radio = getProgress() * 1.0f / getMax();
        boolean noNeedUnReach = false;

//        draw reach bar
        String text = getProgress() + "%";
        int textWidth = (int) mPaint.measureText(text);
        float progressX = radio * mRealWidth;
        if (progressX + textWidth > mRealWidth) {
            progressX = mRealWidth - textWidth;
            noNeedUnReach = true;
        }
        float endX = radio * mRealWidth - mTextOffset / 2;
        if (endX > 0) {
            mPaint.setColor(mReachColor);
            mPaint.setStrokeWidth(mReachHeight);
            canvas.drawLine(0, 0, endX, 0, mPaint);
        }

//        draw text
        mPaint.setColor(mTextColor);
        int y = (int) ((mPaint.descent() + mPaint.ascent()) / 2);
        canvas.drawText(text, progressX, -y, mPaint);

//        draw unreach bar
        if (!noNeedUnReach) {
            float start = progressX + mTextOffset / 2 + textWidth;
            mPaint.setColor(mUnReachColor);
            mPaint.setStrokeWidth(mUnReachHeight);
            canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
        }

        canvas.restore();
    }

    private int dp2px(int dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue,
                getResources().getDisplayMetrics());
    }
    private int sp2px(int spValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, spValue,
                getResources().getDisplayMetrics());
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值