1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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
15 */
16
17package com.android.phone.common.dialpad;
18
19import android.content.Context;
20import android.graphics.Canvas;
21import android.graphics.Paint;
22import android.graphics.Rect;
23import android.util.AttributeSet;
24import android.widget.TextView;
25
26/**
27 * This is a custom text view intended only for rendering the numerals (and star and pound) on the
28 * dialpad. TextView has built in top/bottom padding to help account for ascenders/descenders.
29 *
30 * Since vertical space is at a premium on the dialpad, particularly if the font size is scaled to
31 * a larger default, for the dialpad we use this class to more precisely render characters according
32 * to the precise amount of space they need.
33 */
34public class DialpadTextView extends TextView {
35    private Rect mTextBounds = new Rect();
36    private String mTextStr;
37
38    public DialpadTextView(Context context, AttributeSet attrs) {
39        super(context, attrs);
40    }
41
42    /**
43     * Draw the text to fit within the height/width which have been specified during measurement.
44     */
45    @Override
46    public void draw(Canvas canvas) {
47        Paint paint = getPaint();
48
49        // Without this, the draw does not respect the style's specified text color.
50        paint.setColor(getCurrentTextColor());
51
52        // The text bounds values are relative and can be negative,, so rather than specifying a
53        // standard origin such as 0, 0, we need to use negative of the left/top bounds.
54        // For example, the bounds may be: Left: 11, Right: 37, Top: -77, Bottom: 0
55        canvas.drawText(mTextStr, -mTextBounds.left, -mTextBounds.top, paint);
56    }
57
58    /**
59     * Calculate the pixel-accurate bounds of the text when rendered, and use that to specify the
60     * height and width.
61     */
62    @Override
63    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
64        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
65        mTextStr = getText().toString();
66        getPaint().getTextBounds(mTextStr, 0, mTextStr.length(), mTextBounds);
67
68        int width = resolveSize(mTextBounds.width(), widthMeasureSpec);
69        int height = resolveSize(mTextBounds.height(), heightMeasureSpec);
70        setMeasuredDimension(width, height);
71    }
72}
73