概述
简单实现的一个显示电池的电量的View,具体看代码
public class MainActivity extends Activity {
BatteryView mBatteryView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBatteryView = (BatteryView) findViewById(R.id.battery_view);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
register();
}
@Override
protected void onPause() {
super.onPause();
unregister();
}
private void register() {
registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private void unregister() {
unregisterReceiver(batteryChangedReceiver);
}
// 接受广播
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
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;
Log.d("Deom", "电池电量::" + power);
mBatteryView.setPower(power);
}
}
};
}
public class BatteryView extends View{
private int mPower = 100;
public BatteryView(Context context) {
super(context);
}
public BatteryView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int battery_left = 0;
int battery_top = 0;
int battery_width = 25;
int battery_height = 15;
int battery_head_width = 3;
int battery_head_height = 3;
int battery_inside_margin = 3;
//先画外框
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
Rect rect = new Rect(battery_left, battery_top,
battery_left + battery_width, battery_top + battery_height);
canvas.drawRect(rect, paint);
float power_percent = mPower / 100.0f;
Paint paint2 = new Paint(paint);
paint2.setStyle(Style.FILL);
//画电量
if(power_percent != 0) {
int p_left = battery_left + battery_inside_margin;
int p_top = battery_top + battery_inside_margin;
int p_right = p_left - battery_inside_margin + (int)((battery_width - battery_inside_margin) * power_percent);
int p_bottom = p_top + battery_height - battery_inside_margin * 2;
Rect rect2 = new Rect(p_left, p_top, p_right , p_bottom);
canvas.drawRect(rect2, paint2);
}
//画电池头
int h_left = battery_left + battery_width;
int h_top = battery_top + battery_height / 2 - battery_head_height / 2;
int h_right = h_left + battery_head_width;
int h_bottom = h_top + battery_head_height;
Rect rect3 = new Rect(h_left, h_top, h_right, h_bottom);
canvas.drawRect(rect3, paint2);
}
public void setPower(int power) {
mPower = power;
if(mPower < 0) {
mPower = 0;
}
invalidate();
}
}
效果如下:
最后
以上就是秀丽大山为你收集整理的Android自定义电池,Android显示电量——自定义电池View的全部内容,希望文章能够帮你解决Android自定义电池,Android显示电量——自定义电池View所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复