电量View,效果如下:
1电量组件
主要分三部分电池的外框,电池的头和电量。
/**
* 电量显示控件
*/
public class BatteryStateView extends View {
private int mPower = 100;
public BatteryStateView(Context context) {
super(context);
}
public BatteryStateView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int batteryLeft = 0;
int batteryTop = 2;
int batteryWidth = 60;//电池的宽
int batteryHeight = 25;//电池的高
int batteryHeadWidth = 6;//头部的宽
int batteryHeadHeight = 6;//头部的高
int batteryInsideMargin = 3;
//先画外框
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
Rect rect = new Rect(batteryLeft, batteryTop, batteryLeft + batteryWidth, batteryTop + batteryHeight);
canvas.drawRect(rect, paint);
//画电池头
Paint paintHead = new Paint(paint);
paintHead.setColor(Color.WHITE);
paintHead.setStyle(Style.FILL);
int headLeft = batteryLeft + batteryWidth;
int headTop = batteryTop + batteryHeight / 2 - batteryHeadHeight / 2;
int headRight = headLeft + batteryHeadWidth;
int headBottom = headTop + batteryHeadHeight;
Rect headRect = new Rect(headLeft, headTop, headRight, headBottom);
canvas.drawRect(headRect, paintHead);
//画电量
float powerPercent = mPower / 100.0f;
Paint paintBattery = new Paint(paint);
paintBattery.setColor(Color.GREEN);
paintBattery.setStyle(Style.FILL);
if (powerPercent != 0) {
int pLeft = batteryLeft + batteryInsideMargin;
int pTop = batteryTop + batteryInsideMargin;
int pRight = pLeft - batteryInsideMargin + (int) ((batteryWidth - batteryInsideMargin) * powerPercent);
int pBottom = pTop + batteryHeight - batteryInsideMargin * 2;
Rect powerPercentRect = new Rect(pLeft, pTop, pRight, pBottom);
canvas.drawRect(powerPercentRect, paintBattery);
}
}
public void setPower(int power) {
mPower = power;
if (mPower < 0)
mPower = 0;
invalidate();
}
}
2 电量监听
监听电量发生改变的事件。
/**
* 电量显示工具类
*/
public class BatteryStateViewUtil {
/**
* 创建电量监听
* @param view
* @return
*/
public static BroadcastReceiver createBroadcastReceiver(BatteryStateView view) {
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
int power = level * 100 / scale;
view.setPower(power);
}
}
};
}
}
3 Avtivity中添加监听
@Override
protected void onResume() {
register();
super.onResume();
}
@Override
protected void onPause() {
unregister();
super.onPause();
}
/**注册*/
public void register() {
if (batteryChangedReceiver == null)
batteryChangedReceiver = BatteryStateViewUtil.createBroadcastReceiver(binding.batteryStateView);//binding.batteryStateView是电量的组件
registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
/**取消注册*/
public void unregister() {
unregisterReceiver(batteryChangedReceiver);
}