自定义view实现下载进度button

先看效果图
marc专属

这里写图片描述

这里有个小问题。完成的时候应该显示 完成。这个随意了

下面直接开撸:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class ProgressButton extends Button {
private boolean mProgressEnable;
private long mMax = 100;
private long mProgress;
private Drawable mProgressDrawable;
/**设置是否允许进度*/
public void setProgressEnable(boolean progressEnable) {
mProgressEnable = progressEnable;
}
/**设置进度的最大值*/
public void setMax(long max) {
mMax = max;
}
/**设置当前的进度,并且进行重绘操作*/
public void setProgress(long progress) {
mProgress = progress;
invalidate();
}
/**设置progressButton的进度图片*/
public void setProgressDrawable(Drawable progressDrawable) {
mProgressDrawable = progressDrawable;
}
public ProgressButton(Context context) {
super(context);
}
public ProgressButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
if(mProgressEnable){
Drawable drawable = new ColorDrawable(Color.BLUE);
int left = 0;
int top = 0;
int right = (int) (mProgress * 1.0f / mMax * getMeasuredWidth() + .5f);
int bottom = getBottom();
drawable.setBounds(left, top, right, bottom);// 必须的.告知绘制的范围
drawable.draw(canvas);
}
super.onDraw(canvas);// 绘制文本,还会绘制背景
}
}

自定义view中,如果直接继承自现有控件的话,那么在ondraw方法中,可以去选择性的在super前面或者后面写一些方法

在xml中使用:

1
2
3
4
5
6
7
8
9
10
11
<com.tescoo.aat.widget.ProgressButton
android:id="@+id/app_detail_download_btn_download"
android:layout_width="match_parent"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_toLeftOf="@id/app_detail_download_btn_share"
android:layout_toRightOf="@id/app_detail_download_btn_favo"
android:text="下载"
android:textColor="@android:color/white" />

使用之前记得
mProgressButton.setBackgroundResource(R.drawable.selector_app_detail_bottom_normal);

mProgressButton.setBackgroundResource(R.drawable.selector_app_detail_bottom_downloading);

selector_app_detail_bottom_downloading

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/progress_btn_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/progress_bg"></item>
</selector>

selector_app_detail_bottom_normal

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/progress_btn_pressed"></item>
<item android:drawable="@drawable/progress_btn_normal"></item>
</selector>