1 /* 2 * Copyright (C) 2016 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.deskclock.widget; 18 19 import android.content.Context; 20 import android.util.AttributeSet; 21 import android.widget.TextClock; 22 23 /** 24 * Wrapper around TextClock that automatically re-sizes itself to fit within the given bounds. 25 */ 26 public class AutoSizingTextClock extends TextClock { 27 28 private final TextSizeHelper mTextSizeHelper; 29 private boolean mSuppressLayout = false; 30 AutoSizingTextClock(Context context)31 public AutoSizingTextClock(Context context) { 32 this(context, null); 33 } 34 AutoSizingTextClock(Context context, AttributeSet attrs)35 public AutoSizingTextClock(Context context, AttributeSet attrs) { 36 this(context, attrs, 0); 37 } 38 AutoSizingTextClock(Context context, AttributeSet attrs, int defStyleAttr)39 public AutoSizingTextClock(Context context, AttributeSet attrs, int defStyleAttr) { 40 super(context, attrs, defStyleAttr); 41 mTextSizeHelper = new TextSizeHelper(this); 42 } 43 44 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)45 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 46 mTextSizeHelper.onMeasure(widthMeasureSpec, heightMeasureSpec); 47 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 48 } 49 50 @Override onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)51 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 52 super.onTextChanged(text, start, lengthBefore, lengthAfter); 53 if (mTextSizeHelper != null) { 54 if (lengthBefore != lengthAfter) { 55 mSuppressLayout = false; 56 } 57 mTextSizeHelper.onTextChanged(lengthBefore, lengthAfter); 58 } else { 59 requestLayout(); 60 } 61 } 62 63 @Override setText(CharSequence text, BufferType type)64 public void setText(CharSequence text, BufferType type) { 65 mSuppressLayout = true; 66 super.setText(text, type); 67 mSuppressLayout = false; 68 } 69 70 @Override requestLayout()71 public void requestLayout() { 72 if (mTextSizeHelper == null || !mTextSizeHelper.shouldIgnoreRequestLayout()) { 73 if (!mSuppressLayout) { 74 super.requestLayout(); 75 } 76 } 77 } 78 }