1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5  * except in compliance with the License. You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the
10  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11  * KIND, either express or implied. See the License for the specific language governing
12  * permissions and limitations under the License.
13  */
14 
15 package com.android.settings.fuelgauge;
16 
17 import android.content.Context;
18 import android.graphics.Canvas;
19 import android.graphics.Paint;
20 import android.util.AttributeSet;
21 import android.util.SparseIntArray;
22 import android.view.View;
23 
24 import androidx.annotation.Nullable;
25 
26 public class BatteryActiveView extends View {
27 
28     private final Paint mPaint = new Paint();
29     private BatteryActiveProvider mProvider;
30 
BatteryActiveView(Context context, @Nullable AttributeSet attrs)31     public BatteryActiveView(Context context, @Nullable AttributeSet attrs) {
32         super(context, attrs);
33     }
34 
setProvider(BatteryActiveProvider provider)35     public void setProvider(BatteryActiveProvider provider) {
36         mProvider = provider;
37         if (getWidth() != 0) {
38             postInvalidate();
39         }
40     }
41 
42     @Override
onSizeChanged(int w, int h, int oldw, int oldh)43     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
44         super.onSizeChanged(w, h, oldw, oldh);
45         if (getWidth() != 0) {
46             postInvalidate();
47         }
48     }
49 
50     @Override
onDraw(Canvas canvas)51     protected void onDraw(Canvas canvas) {
52         if (mProvider == null) {
53             return;
54         }
55         SparseIntArray array = mProvider.getColorArray();
56         float period = mProvider.getPeriod();
57         for (int i = 0; i < array.size() - 1; i++) {
58             drawColor(canvas, array.keyAt(i), array.keyAt(i + 1), array.valueAt(i), period);
59         }
60     }
61 
drawColor(Canvas canvas, int start, int end, int color, float period)62     private void drawColor(Canvas canvas, int start, int end, int color, float period) {
63         if (color == 0) {
64             return;
65         }
66         mPaint.setColor(color);
67         canvas.drawRect(
68                 start / period * getWidth(), 0, end / period * getWidth(), getHeight(), mPaint);
69     }
70 
71     public interface BatteryActiveProvider {
hasData()72         boolean hasData();
73 
getPeriod()74         long getPeriod();
75 
getColorArray()76         SparseIntArray getColorArray();
77     }
78 }
79