Home | History | Annotate | Download | only in widget
      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.support.v7.widget.AppCompatTextView;
     21 import android.util.AttributeSet;
     22 
     23 /**
     24  * A TextView which automatically re-sizes its text to fit within its boundaries.
     25  */
     26 public class AutoSizingTextView extends AppCompatTextView {
     27 
     28     private final TextSizeHelper mTextSizeHelper;
     29 
     30     public AutoSizingTextView(Context context) {
     31         this(context, null);
     32     }
     33 
     34     public AutoSizingTextView(Context context, AttributeSet attrs) {
     35         this(context, attrs, android.R.attr.textViewStyle);
     36     }
     37 
     38     public AutoSizingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
     39         super(context, attrs, defStyleAttr);
     40         mTextSizeHelper = new TextSizeHelper(this);
     41     }
     42 
     43     @Override
     44     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     45         mTextSizeHelper.onMeasure(widthMeasureSpec, heightMeasureSpec);
     46         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     47     }
     48 
     49     @Override
     50     protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
     51         super.onTextChanged(text, start, lengthBefore, lengthAfter);
     52         if (mTextSizeHelper != null) {
     53             mTextSizeHelper.onTextChanged(lengthBefore, lengthAfter);
     54         } else {
     55             requestLayout();
     56         }
     57     }
     58 
     59     @Override
     60     public void requestLayout() {
     61         if (mTextSizeHelper == null || !mTextSizeHelper.shouldIgnoreRequestLayout()) {
     62             super.requestLayout();
     63         }
     64     }
     65 }