blob: 91ad0dde5df8ffb808b7792c6addf6df5791d2e5 [file] [log] [blame]
Justin Klaassen44595162015-05-28 17:55:20 -07001/*
2 * Copyright (C) 2015 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.calculator2;
18
19import android.content.Context;
20import android.graphics.Paint;
21import android.graphics.Rect;
Justin Klaassen44595162015-05-28 17:55:20 -070022import android.util.AttributeSet;
23import android.widget.TextView;
24
Justin Klaassen44595162015-05-28 17:55:20 -070025/**
26 * Extended {@link TextView} that supports ascent/baseline alignment.
27 */
28public class AlignedTextView extends TextView {
29
30 private static final String LATIN_CAPITAL_LETTER = "H";
Justin Klaassen44595162015-05-28 17:55:20 -070031
32 // temporary rect for use during layout
33 private final Rect mTempRect = new Rect();
34
35 private int mTopPaddingOffset;
36 private int mBottomPaddingOffset;
37
38 public AlignedTextView(Context context) {
39 this(context, null /* attrs */);
40 }
41
42 public AlignedTextView(Context context, AttributeSet attrs) {
43 this(context, attrs, android.R.attr.textViewStyle);
44 }
45
46 public AlignedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
47 super(context, attrs, defStyleAttr);
48
49 // Disable any included font padding by default.
50 setIncludeFontPadding(false);
51 }
52
53 @Override
54 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Justin Klaassenb2c3e442015-06-30 19:02:25 -070055 final Paint paint = getPaint();
Justin Klaassen44595162015-05-28 17:55:20 -070056
Justin Klaassenb2c3e442015-06-30 19:02:25 -070057 // Always align text to the default capital letter height.
58 paint.getTextBounds(LATIN_CAPITAL_LETTER, 0, 1, mTempRect);
59
Justin Klaassen44595162015-05-28 17:55:20 -070060 mTopPaddingOffset = Math.min(getPaddingTop(),
Justin Klaassenb2c3e442015-06-30 19:02:25 -070061 (int) Math.ceil(mTempRect.top - paint.ascent()));
62 mBottomPaddingOffset = Math.min(getPaddingBottom(), (int) Math.ceil(paint.descent()));
Justin Klaassen44595162015-05-28 17:55:20 -070063
64 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
65 }
66
67 @Override
68 public int getCompoundPaddingTop() {
69 return super.getCompoundPaddingTop() - mTopPaddingOffset;
70 }
71
72 @Override
73 public int getCompoundPaddingBottom() {
74 return super.getCompoundPaddingBottom() - mBottomPaddingOffset;
75 }
76}