2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.settings.deviceinfo;
19 import com.android.settings.R;
21 import android.content.Context;
22 import android.content.res.TypedArray;
23 import android.graphics.Canvas;
24 import android.graphics.Color;
25 import android.graphics.Paint;
26 import android.util.AttributeSet;
27 import android.view.View;
29 import java.util.Collection;
34 public class PercentageBarChart extends View {
35 private final Paint mEmptyPaint = new Paint();
37 private Collection<Entry> mEntries;
39 public static class Entry {
40 public final float percentage;
41 public final Paint paint;
43 protected Entry(float percentage, Paint paint) {
44 this.percentage = percentage;
49 public PercentageBarChart(Context context, AttributeSet attrs) {
50 super(context, attrs);
52 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PercentageBarChart, 0, 0);
54 int emptyColor = Color.BLACK;
56 int n = a.getIndexCount();
57 for (int i = 0; i < n; i++) {
58 int attr = a.getIndex(i);
61 case R.styleable.PercentageBarChart_emptyColor:
62 emptyColor = a.getColor(attr, 0);
69 mEmptyPaint.setColor(emptyColor);
70 mEmptyPaint.setStyle(Paint.Style.FILL);
74 protected void onDraw(Canvas canvas) {
77 final int left = getPaddingLeft();
78 final int right = getWidth() - getPaddingRight();
79 final int top = getPaddingTop();
80 final int bottom = getHeight() - getPaddingBottom();
82 final int width = right - left;
86 if (mEntries != null) {
87 for (final Entry e : mEntries) {
89 if (e.percentage == 0f) {
92 entryWidth = Math.max(1, (int) (width * e.percentage));
95 final int nextX = lastX + entryWidth;
100 canvas.drawRect(lastX, top, nextX, bottom, e.paint);
105 canvas.drawRect(lastX, top, lastX + width, bottom, mEmptyPaint);
109 * Sets the background for this chart. Callers are responsible for later
110 * calling {@link #invalidate()}.
112 public void setBackgroundColor(int color) {
113 mEmptyPaint.setColor(color);
117 * Adds a new slice to the percentage bar chart. Callers are responsible for
118 * later calling {@link #invalidate()}.
120 * @param percentage the total width that
121 * @param color the color to draw the entry
123 public static Entry createEntry(float percentage, int color) {
124 final Paint p = new Paint();
126 p.setStyle(Paint.Style.FILL);
128 return new Entry(percentage, p);
131 public void setEntries(Collection<Entry> entries) {