让按钮具有显示进度的效果,节省布局空间,先看看效果:
主要的逻辑:根据下载进度的百分比和button的宽度得到一个进度的宽度,绘制一个以此为宽度的背景设置给button,随着下载进度这个button的背景不断变化。
下载的进度我们暂时用模拟;
button宽高的获得,在onclick事件中
w = v.getMeasuredWidth();
h = v.getMeasuredHeight();
模拟下载使用异步任务:
class DownloadTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
for (int i = 0; i < max; i++) {
publishProgress(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
bt.setText("点击安装");
bt.setClickable(true);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "开始安装", Toast.LENGTH_LONG)
.show();
}
});
}
@Override
protected void onPreExecute() {
super.onPreExecute();
bt.setClickable(false);
}
@Override
protected void onProgressUpdate(Integer... values) {
Drawable d = createDrawable(Color.parseColor("#8e375a"), values[0]);
float f = values[0] * 1.0f;
String s = new DecimalFormat("#.#").format(f);
bt.setText("已下载" + (f < 10 ? "0" : "") + s + "%");
bt.setBackgroundDrawable(d);
}
}
得到一个指定宽度的Drawable方法
public BitmapDrawable createDrawable(int color, int length) {
Bitmap b = null;
b = Bitmap.createBitmap(w, h, Config.ARGB_4444);
Canvas c = new Canvas(b);
// RectF rect = new RectF(0, 0, length, h);
RectF rect = new RectF(0, 0, w * (length * 1.0f / max), h);
p.setColor(color);
c.drawRoundRect(rect, 10, 10, p);
BitmapDrawable bd = new BitmapDrawable(b);
return bd;
}
加点圆角,看着美观一点。
将两种控件结合,还是能给我们平时的设计一点启示的。