1 /* 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 17 package com.android.systemui.volume; 18 19 import android.content.Context; 20 import android.content.res.Resources; 21 import android.util.ArrayMap; 22 import android.util.TypedValue; 23 import android.view.View; 24 import android.view.View.OnAttachStateChangeListener; 25 import android.widget.TextView; 26 27 /** 28 * Capture initial sp values for registered textviews, and update properly when configuration 29 * changes. 30 */ 31 public class SpTexts { 32 33 private final Context mContext; 34 private final ArrayMap<TextView, Integer> mTexts = new ArrayMap<>(); 35 SpTexts(Context context)36 public SpTexts(Context context) { 37 mContext = context; 38 } 39 add(final TextView text)40 public int add(final TextView text) { 41 if (text == null) return 0; 42 final Resources res = mContext.getResources(); 43 final float fontScale = res.getConfiguration().fontScale; 44 final float density = res.getDisplayMetrics().density; 45 final float px = text.getTextSize(); 46 final int sp = (int)(px / fontScale / density); 47 mTexts.put(text, sp); 48 text.addOnAttachStateChangeListener(new OnAttachStateChangeListener() { 49 @Override 50 public void onViewDetachedFromWindow(View v) { 51 } 52 53 @Override 54 public void onViewAttachedToWindow(View v) { 55 setTextSizeH(text, sp); 56 } 57 }); 58 return sp; 59 } 60 update()61 public void update() { 62 if (mTexts.isEmpty()) return; 63 mTexts.keyAt(0).post(mUpdateAll); 64 } 65 setTextSizeH(TextView text, int sp)66 private void setTextSizeH(TextView text, int sp) { 67 text.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp); 68 } 69 70 private final Runnable mUpdateAll = new Runnable() { 71 @Override 72 public void run() { 73 for (int i = 0; i < mTexts.size(); i++) { 74 setTextSizeH(mTexts.keyAt(i), mTexts.valueAt(i)); 75 } 76 } 77 }; 78 } 79