Skip to content Skip to sidebar Skip to footer

Dynamically Resize Font Of Textview

Is it possible to dynamically re-size fonts in a textview according to screen resolution? If yes how? I'm developing from an mdpi avd. But when the app is installed on hdpi text ap

Solution 1:

Use textSize and the scaled pixels sp unit is what alextsc is implying.

If you realy want to be dynmic and make you font as big as possible to fill up the width then it is possible with a textWatcher to render the text and check the size and then tweak the fonts on the fly.

The following is rather specific as I have multiple text views in a linear layout and this only resizes the text smaller once the text in one of them will not fit. It will give you something to work with though.

classLineTextWatcherimplementsTextWatcher {

staticfinalStringTAG="IpBike";
TextView mTV;
Paint mPaint;

publicLineTextWatcher(TextView text) {
    mTV = text;
    mPaint = newPaint();
}

publicvoidbeforeTextChanged(CharSequence s, int start, int count,
        int after) {
}

publicvoidonTextChanged(CharSequence s, int start, int before, int count) {
}

publicvoidafterTextChanged(Editable s) {
    // do the work here.// we are looking for the text not fitting.ViewParentvp= mTV.getParent();
    if ((vp != null) && (vp instanceof LinearLayout)) {
        LinearLayoutparent= (LinearLayout) vp;
        if (parent.getVisibility() == View.VISIBLE) {
            mPaint.setTextSize(mTV.getTextSize());
            finalfloatsize= mPaint.measureText(s.toString());
            if ((int) size > mTV.getWidth()) {
                floatts= mTV.getTextSize();
                Log.w(TAG, "Text ellipsized TextSize was: " + ts);
                for (inti=0; i < parent.getChildCount(); i++) {
                    Viewchild= parent.getChildAt(i);
                    if ((child != null) && (child instanceof TextView)) {
                        TextViewtv= (TextView) child;
                        // first off we want to keep the verticle// height.
                        tv.setHeight(tv.getHeight()); // freeze the// height.

                        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                                tv.getTextSize() - 1);
                    } else {
                        Log.v(TAG, "afterTextChanged Child not textView");
                    }
                }
            }
        }
    } else {
        Log.v(TAG, "afterTextChanged parent not LinearLayout");
    }
}
}

Post a Comment for "Dynamically Resize Font Of Textview"