顯示電量自定義View,外部不須要任何控制,直接添加布局View便可。java
實現三種狀態:canvas
一、未充電時,顯示黑色。ide
二、電量小於20%,顯示紅色。佈局
三、充電狀態顯示綠色post
先看效果圖以下(不知道GIF怎麼上傳,就這樣看吧......):this
代碼以下:線程
public class BatteryView extends View { private int mPower = 100; // 電池電量 private int width; // 電池總寬度 private int height; // 電池總高度 private int margin = 2; // 電池內芯與邊框距離 private int border = 2; // 電池邊框線條寬度 private float radius = 4; // 圓角角度 private boolean isCharge = false; private int chargePower; private Timer mTimer; public BatteryView(Context context) { super(context); } public BatteryView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); width = getMeasuredWidth(); height = getMeasuredHeight(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = getMeasuredWidth(); height = getMeasuredHeight(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setAntiAlias(true);// 去鋸齒 paint.setColor(Color.BLACK);// 設置畫筆顏色 float headWidth = width / 20.0f;// 電池頭寬度 // 畫邊框 paint.setStyle(Paint.Style.STROKE);// 設置空心矩形 paint.setStrokeWidth(border); RectF rect_1 = new RectF(border / 2, border / 2, width - headWidth - border / 2, height - border / 2); canvas.drawRoundRect(rect_1, radius, radius, paint); // 畫電池頭 paint.setStyle(Paint.Style.FILL); paint.setStrokeWidth(0); RectF rect_2 = new RectF(width - headWidth - border / 2, height * 0.25f, width, height * 0.75f); canvas.drawRect(rect_2, paint); // 畫電量 if (isCharge) { paint.setColor(Color.GREEN); } else { if (mPower < 20) { paint.setColor(Color.RED); } else { paint.setColor(Color.BLACK); } } float offset = (width - headWidth - border - margin) * mPower / 100.f; RectF rect_3 = new RectF(border + margin, border + margin, offset, height - border - margin); canvas.drawRoundRect(rect_3, radius, radius, paint); } /** * 設置電量 * * @param mPower 電量百分比 1-100 */ public void setPower(@IntRange(from = 1, to = 100) int mPower) { this.mPower = mPower; if (this.mPower < 0) { this.mPower = 0; } if (this.mPower > 100) { this.mPower = 100; } postInvalidate(); } /** * 獲取電量 * * @return 電量百分比 1-100 */ public int getPower() { return mPower; } /** * 設置充電模式,若是傳入true自動開啓線程,使電池無限循環,營造出一個正在充電的狀態 * * @param charge */ public void setCharge(boolean charge) { isCharge = charge; if (null != mTimer) { mTimer.cancel(); mTimer = null; } if (isCharge) { chargePower = 0; mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { chargePower += 10; if (chargePower > 100) { chargePower = 0; } setPower(chargePower); } }, 500, 300); } } }
用法就不在囉嗦了,比較簡單,至於系統電量能夠經過廣播(Intent.ACTION_BATTERY_CHANGED)獲取。code
結束。。。。。blog