讓按鈕具有顯示進度的效果,節省佈局空間,先看看效果:
主要的邏輯:根據下載進度的百分比和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;
}
加點圓角,看着美觀一點。
將兩種控件結合,還是能給我們平時的設計一點啓示的。