テキストサイズの自動変更について、どなたかご教示頂ければ幸いです。
現在 Android Studioにて、アプリを作成しております。
TextViewに文字列をセットする際に、文字に数に応じてテキストサイズを自動的に変更し、
TextViewの幅に収める仕組みを、
TextViewのフォントサイズを自動調整する。
上サイトに記載のコードを流用しました。
文字をTextViewにセットすると、即時に自動にサイズ変更はされるのですが、
以下の場合には文字サイズが即時に変更されずに、
端末の戻るキーでアプリを閉じ、再起動させた時に変更されます。
・文字数が多い(テキストサイズが小さい)状態から、文字数が少ない状態へ変更する
この条件の場合に(他に条件があるかもしれませんが)反映が即時でないのはなぜでしょうか。
どなたかご教示頂ければ幸いです。
以下にコードを記載致します。
JAVA
1/** 2 * フォントサイズ自動調整TextView 3 */ 4public class FontFitTextView extends AppCompatTextView { 5 /** 6 * コンストラクタ 7 * @param context 8 */ 9 public FontFitTextView(Context context) 10 { 11 super(context); 12 } 13 14 /** 15 * コンストラクタ 16 * @param context 17 * @param attrs 18 */ 19 public FontFitTextView(Context context, AttributeSet attrs) 20 { 21 super(context, attrs); 22 } 23 24 /** 25 * 子Viewの位置を決める 26 */ 27 @Override 28 protected void onLayout(boolean changed, int left, int top, int right, int bottom) 29 { 30 super.onLayout(changed, left, top, right, bottom); 31 resize(); 32 } 33 34 /** 35 * テキストサイズ調整 36 */ 37 private void resize() 38 { 39 40 /** 最小のテキストサイズ */ 41 final float MIN_TEXT_SIZE = 10f; 42 43 int viewHeight = this.getHeight(); // Viewの縦幅 44 int viewWidth = this.getWidth(); // Viewの横幅 45 46 // テキストサイズ 47 float textSize = getTextSize(); 48 49 // Paintにテキストサイズ設定 50 Paint paint = new Paint(); 51 paint.setTextSize(textSize); 52 53 // テキストの縦幅取得 54 FontMetrics fm = paint.getFontMetrics(); 55 float textHeight = (float) (Math.abs(fm.top)) + (Math.abs(fm.descent)); 56 57 // テキストの横幅取得 58 float textWidth = paint.measureText(this.getText().toString()); 59 60 // 縦幅と、横幅が収まるまでループ 61 while (viewHeight < textHeight | viewWidth < textWidth) 62 { 63 // 調整しているテキストサイズが、定義している最小サイズ以下か。 64 if (MIN_TEXT_SIZE >= textSize) 65 { 66 // 最小サイズ以下になる場合は最小サイズ 67 textSize = MIN_TEXT_SIZE; 68 break; 69 } 70 71 // テキストサイズをデクリメント 72 textSize--; 73 74 // Paintにテキストサイズ設定 75 paint.setTextSize(textSize); 76 77 // テキストの縦幅を再取得 78 fm = paint.getFontMetrics(); 79 textHeight = (float) (Math.abs(fm.top)) + (Math.abs(fm.descent)); 80 81 // テキストの横幅を再取得 82 textWidth = paint.measureText(this.getText().toString()); 83 } 84 85 // テキストサイズ設定 86 setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); 87 88 } 89} 90
以上、よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー