Skip to content

Instantly share code, notes, and snippets.

@hackugyo
Last active August 29, 2015 14:06
Show Gist options
  • Save hackugyo/fba989e91dfaeaaf091b to your computer and use it in GitHub Desktop.
Save hackugyo/fba989e91dfaeaaf091b to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontFitTextView">
<attr name="minimumFontSize" format="dimension" />
</declare-styleable>
</resources>
package com.example.glayash.myapplication;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* サイズ自動調整TextView
*
*/
public class FontFitTextView extends TextView {
/** デフォルトの最小のテキストサイズ */
private static final float DEF_MIN_TEXT_SIZE = 10f;
/** 最小のテキストサイズ */
private final float minTextSize;
/**
* コンストラクタ
* @param context
*/
public FontFitTextView(Context context) {
super(context, null);
minTextSize = DEF_MIN_TEXT_SIZE;
}
/**
* コンストラクタ
* @param context
* @param attrs
*/
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.FontFitTextView);
minTextSize = array.getDimension(R.styleable.FontFitTextView_minimumFontSize, getTextSize());
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
resize();
}
/**
* テキストサイズ調整
*/
private void resize() {
Paint paint = new Paint();
// Viewの幅
int viewWidth = this.getWidth();
// テキストサイズ
float textSize = getTextSize();
// Paintにテキストサイズ設定
paint.setTextSize(textSize);
// テキストの横幅取得
float textWidth = paint.measureText(this.getText().toString());
while (viewWidth < textWidth) {
// 横幅に収まるまでループ
if (minTextSize >= textSize) {
// 最小サイズ以下になる場合は最小サイズ
textSize = minTextSize;
break;
}
// テキストサイズをデクリメント
textSize--;
// Paintにテキストサイズ設定
paint.setTextSize(textSize);
// テキストの横幅を再取得
textWidth = paint.measureText(this.getText().toString());
}
// テキストサイズ設定
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment