前幾天看到貝塞爾曲線的時候,想想用貝塞爾做些什麼東西出來。很快一個電量顯示的控制元件就馬上登場了,先來看下效果圖吧:
充電中





看到效果圖基本就這幾種狀態了,這幾種狀態裡面首先分了兩大類:充電中,未充電中;充電中又細分了充電到100%和未達到100%兩種;未充電中又細分了電量低中和電量不在低中的兩種。
原本想的是錄個視訊來模擬充電和未充電兩種情況的,後來生成的gif一直是大於簡書上傳的要求,因此這裡就上傳多個gif了**(為了演示幾種情況,程式碼中狀態是寫死的,因此大家看到的狀態列和控制元件顯示的不一樣)**。demo我都通過動態資料獲取電量測試過了。
使用
- 屬性部分:
屬性名 | 型別 | 描述 |
---|---|---|
ring_stroke_width | dimension | 外圈的寬度 |
ring_radius | dimension | 外圈的半徑 |
wave_width | dimension | 一個波浪的寬度 |
wave_peek | dimension | 波浪的峰值 |
wave_cycle_time | integer | 波浪走動的速度 |
wave_color | color | 波浪的顏色 |
battery_status_color | color | 充電狀態文字顏色 |
battery_status_size | dimension | 充電狀態文字大小 |
battery_level_color | color | 充電百分比文字顏色 |
battery_level_size | dimension | 充電百分比文字大小 |
battery_status_size | dimension | 充電文字狀態顏色 |
battery_lowpower_color | color | 低電量下的文字閃動的顏色 |
battery_charging_text | string或reference | 正在充電的文字 |
battery_fill_text | string或reference | 充滿的文字 |
battery_using_text | string或reference | 正在使用的文字 |
battery_lowpower_text | string或reference | 低電量的文字 |
battery_lowpower_percnet | fraction | 百分之多少時才顯示低電量 |
charging_direction | enum | 充電的時候波浪滾動的方向 |
- 佈區域性分:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#12b3c9"
android:gravity="center"
android:orientation="vertical">
<com.library.battery.BatteryView
android:id="@+id/batteryView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:battery_lowpower_color="#d96d15"
app:battery_lowpower_percnet="10%"
app:ring_radius="@dimen/ring_radius"
app:ring_stroke_width="@dimen/ring_stroke_width"
app:wave_color="#3acf38"
app:wave_cycle_time="1000"
app:wave_peek="@dimen/wave_peek"
app:wave_width="@dimen/wave_width" />
</LinearLayout>
複製程式碼
佈局中用到的屬性不是全的,就拿了幾個試試。想要看更多的屬性自己新增吧。效果圖如下:

- 程式碼部分:
public class MainActivity extends AppCompatActivity {
BatteryView batteryView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryView = (BatteryView) findViewById(R.id.batteryView);
batteryView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
batteryView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(new BatteryReceiver(), filter);
}
});
}
public void setBattery(BatteryStatus status) {
Log.d("TAG", "status:" + status.status + ",level:" +status.level);
batteryView.setChanges(status.status, status.level);
}
}
複製程式碼
切記:這裡呼叫BatteryView的setChange方法必須要在layout都載入完才能呼叫該方法。
關於我:
email: a1002326270@163.com
github: enter