寒川アクアブログ

美容師しながらアプリ開発していて水草が趣味の私のブログです

フォントサイズを自動調整するテキストビュー

テキストビューに文字列を表示させる際、
文字列がテキストビューの縦・横幅にぴったり納まるように
フォントサイズを自動調整するテキストビューです。

こちらのサイトを参考にさせていただきました!
思った通りのレイアウトができ、本当に助かりました。ありがとうございます!
monakap.hatenablog.com

テキストビューを継承したクラスです
public class AutoResizeTextView extends TextView {

    private  final float MIN_TEXT_SIZE = 10f;

    public AutoResizeTextView(Context context) {
        super(context);
    }

    public AutoResizeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        resize();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        resize();
    }

    private void resize() {

        Paint paint = new Paint();

        int viewWidth = this.getWidth();
        int viewHeight = this.getHeight();

        //    適当に大きめの数値からスタート
        float textSize = 300f;

        paint.setTextSize(textSize);

        Paint.FontMetrics fm = paint.getFontMetrics();
        float textHeight = (float)(Math.abs(fm.top)) + (Math.abs(fm.descent));

        float textWidth = paint.measureText(this.getText().toString());
        while (viewWidth < textWidth | viewHeight < textHeight){
            if (MIN_TEXT_SIZE >= textSize){
                textSize = MIN_TEXT_SIZE;
                break;
            }

            textSize--;

            paint.setTextSize(textSize);

            fm = paint.getFontMetrics();
            textHeight = (float)(Math.abs(fm.top)) + (Math.abs(fm.descent));
            textWidth = paint.measureText(this.getText().toString());
        }
        setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    }

}


前途のサイトに各処理の詳細が掲載されています。
非常にわかりやすいのでぜひご覧ください。


また、宣伝みたいになってしまいますが、
このテキストビューに、タップした時に色を暗くする機能
ボタンをタップした時に動的に色を変える方法 - kojiko-android’s blog
を持たせ、ボタンとして活用した電卓アプリを作りました。
全てのボタン、メインディスプレイ等を全部を、こちらのカスタムテキストビューを継承して使っています。
それぞれ、サイズ調整の際に、サイズを1づつデクリメントしているので、
やや重くなってしまいましたが、
端末の画面サイズが変わっても狙い通りのレイアウトになるので、
とても重宝しています。
よろしかったらお試しください!
play.google.com

今後の課題は、ボタンらしい影を追加すること。
大変そう・・・笑