自定义View简单操作之下载进度条按钮

这里实现下载进度条按钮的一个简单效果,主要是了解自定义View的一些常用的方法,drawRoundRect(),drawText()等,下面是代码块

public classProgressButtonextendsTextView {

private static finalStringTAG="ProgressButton";

PaintmPaint,mTextPaint;

private intwidth,height,space,radius,progress;

private intprogressbtn_backgroud_color,progressbtn_backgroud_second_color;

//动画执行100.

private booleanisStart=false;

privateStringtext;

publicProgressButton(Context context) {

super(context);

}

publicProgressButton(Context context,@NullableAttributeSet attrs) {

super(context,attrs);

initPaint();

}

publicProgressButton(Context context,@NullableAttributeSet attrs, intdefStyleAttr) {

super(context,attrs,defStyleAttr);

}

private voidinitPaint() {

mPaint=newPaint();

progressbtn_backgroud_color= getContext().getResources().getColor(R.color.progressbtn_backgroud_color);

progressbtn_backgroud_second_color= getContext().getResources().getColor(R.color.progressbtn_backgroud_second_color);

mPaint.setColor(progressbtn_backgroud_color);

mPaint.setAntiAlias(true);

radius= DisplayUtil.dip2px(getContext(),8);

//文字画笔

mTextPaint=newPaint();

mTextPaint.setColor(Color.WHITE);

mTextPaint.setAntiAlias(true);

mTextPaint.setTextSize(DisplayUtil.sp2px(getContext(),14));

}

@Override

protected voidonDraw(Canvas canvas) {

super.onDraw(canvas);

//背景

mPaint.setColor(progressbtn_backgroud_color);

RectF r1 =newRectF(0,0,width,height);

canvas.drawRoundRect(r1,radius,radius,mPaint);

//进度

mPaint.setColor(progressbtn_backgroud_second_color);

intnewWidth =progress*space;

if(newWidth >=width) {

newWidth =width;

}

RectF r2 =newRectF(0,0,newWidth,height);

canvas.drawRoundRect(r2,radius,radius,mPaint);

//字体

if(progress==0) {

text="开始";

}else if(progress>=100) {

text="结束";

}else{

text="下载中 "+progress+" % ";

}

//获取文字的高宽

Rect rect =newRect();

mTextPaint.getTextBounds(text,0,text.length(),rect);

inttextWidth = rect.width();//文本的宽度

canvas.drawText(text,(width- textWidth) /2,height/2,mTextPaint);

postDelayed(runnable,30);

}

privateRunnablerunnable=newRunnable() {

@Override

public voidrun() {

if(!isStart) {

return;

}

if(progress>100) {

return;

}

progress++;

postInvalidate();

}

};

public voidstart() {

//进度

isStart=true;

post(runnable);

}

public voidpause() {

//进度

isStart=false;

post(runnable);

}

@Override

protected voidonSizeChanged(intw, inth, intoldw, intoldh) {

super.onSizeChanged(w,h,oldw,oldh);

width= w;

height= h;

space=width%100==0? w /100: (w /100) +1;

}

@Override

protected voidonFinishInflate() {

super.onFinishInflate();

setOnClickListener(newOnClickListener() {

@Override

public voidonClick(View view) {

if(isStart) {

pause();

}else{

start();

}

}

});

}

@Override

protected voidonDetachedFromWindow() {

super.onDetachedFromWindow();

if(runnable!=null) {

removeCallbacks(runnable);

}

}

}

项目地址:gitee.com/401328080/ProgressButton

你可能感兴趣的:(自定义View简单操作之下载进度条按钮)