Guest User

Untitled

a guest
Oct 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import android.content.Context;
  2. import android.graphics.Paint;
  3. import android.util.AttributeSet;
  4. import android.util.TypedValue;
  5. import android.widget.TextView;
  6.  
  7. /**
  8. * サイズ自動調整TextView
  9. *
  10. */
  11. public class FontFitTextView extends TextView {
  12.  
  13. /** 最小のテキストサイズ */
  14. private static final float MIN_TEXT_SIZE = 10f;
  15.  
  16. /**
  17. * コンストラクタ
  18. * @param context
  19. */
  20. public FontFitTextView(Context context) {
  21. super(context);
  22. }
  23.  
  24. /**
  25. * コンストラクタ
  26. * @param context
  27. * @param attrs
  28. */
  29. public FontFitTextView(Context context, AttributeSet attrs) {
  30. super(context, attrs);
  31. }
  32.  
  33. @Override
  34. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  35. super.onLayout(changed, left, top, right, bottom);
  36.  
  37. resize();
  38.  
  39. }
  40.  
  41. /**
  42. * テキストサイズ調整
  43. */
  44. private void resize() {
  45.  
  46. Paint paint = new Paint();
  47.  
  48. // Viewの幅
  49. int viewWidth = this.getWidth();
  50. // テキストサイズ
  51. float textSize = getTextSize();
  52.  
  53. // Paintにテキストサイズ設定
  54. paint.setTextSize(textSize);
  55. // テキストの横幅取得
  56. float textWidth = paint.measureText(this.getText().toString());
  57.  
  58. while (viewWidth < textWidth) {
  59. // 横幅に収まるまでループ
  60.  
  61. if (MIN_TEXT_SIZE >= textSize) {
  62. // 最小サイズ以下になる場合は最小サイズ
  63. textSize = MIN_TEXT_SIZE;
  64. break;
  65. }
  66.  
  67. // テキストサイズをデクリメント
  68. textSize--;
  69.  
  70. // Paintにテキストサイズ設定
  71. paint.setTextSize(textSize);
  72. // テキストの横幅を再取得
  73. textWidth = paint.measureText(this.getText().toString());
  74.  
  75. }
  76.  
  77. // テキストサイズ設定
  78. setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
  79. }
  80.  
  81. }
Add Comment
Please, Sign In to add comment