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 17 package com.android.dialer.dialpadview; 18 19 import android.content.Context; 20 import android.graphics.Canvas; 21 import android.graphics.Paint; 22 import android.graphics.Rect; 23 import android.util.AttributeSet; 24 import 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 * <p>Since vertical space is at a premium on the dialpad, particularly if the font size is scaled 31 * to a larger default, for the dialpad we use this class to more precisely render characters 32 * according to the precise amount of space they need. 33 */ 34 public class DialpadTextView extends TextView { 35 36 private Rect mTextBounds = new Rect(); 37 private String mTextStr; 38 DialpadTextView(Context context, AttributeSet attrs)39 public DialpadTextView(Context context, AttributeSet attrs) { 40 super(context, attrs); 41 } 42 43 /** Draw the text to fit within the height/width which have been specified during measurement. */ 44 @Override draw(Canvas canvas)45 public void draw(Canvas canvas) { 46 Paint paint = getPaint(); 47 48 // Without this, the draw does not respect the style's specified text color. 49 paint.setColor(getCurrentTextColor()); 50 51 // The text bounds values are relative and can be negative,, so rather than specifying a 52 // standard origin such as 0, 0, we need to use negative of the left/top bounds. 53 // For example, the bounds may be: Left: 11, Right: 37, Top: -77, Bottom: 0 54 canvas.drawText(mTextStr, -mTextBounds.left, -mTextBounds.top, paint); 55 } 56 57 /** 58 * Calculate the pixel-accurate bounds of the text when rendered, and use that to specify the 59 * height and width. 60 */ 61 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)62 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 63 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 64 mTextStr = getText().toString(); 65 getPaint().getTextBounds(mTextStr, 0, mTextStr.length(), mTextBounds); 66 67 int width = resolveSize(mTextBounds.width(), widthMeasureSpec); 68 int height = resolveSize(mTextBounds.height(), heightMeasureSpec); 69 setMeasuredDimension(width, height); 70 } 71 } 72