How to adjust text font size to fit textview

后端 未结 22 1760
無奈伤痛
無奈伤痛 2020-11-22 05:15

Is there any way in android to adjust the textsize in a textview to fit the space it occupies?

E.g. I\'m using a TableLayout and adding several Te

相关标签:
22条回答
  • 2020-11-22 05:42

    If a tranformation like allCaps is set, speedplane's approach is buggy. I fixed it, resulting in the following code (sorry, my reputation does not allow me to add this as a comment to speedplane's solution):

    import android.content.Context;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.util.TypedValue;
    import android.widget.TextView;
    
    public class FontFitTextView extends TextView {
    
        public FontFitTextView(Context context) {
            super(context);
            initialise();
        }
    
        public FontFitTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initialise();
        }
    
        private void initialise() {
            mTestPaint = new Paint();
            mTestPaint.set(this.getPaint());
            //max size defaults to the initially specified text size unless it is too small
        }
    
        /* Re size the font so the specified text fits in the text box
         * assuming the text box is the specified width.
         */
        private void refitText(String text, int textWidth) 
        { 
            if (getTransformationMethod() != null) {
                text = getTransformationMethod().getTransformation(text, this).toString();
            }
    
            if (textWidth <= 0)
                return;
            int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            float hi = 100;
            float lo = 2;
            final float threshold = 0.5f; // How close we have to be
    
            mTestPaint.set(this.getPaint());
    
            while((hi - lo) > threshold) {
                float size = (hi+lo)/2;
                if(mTestPaint.measureText(text) >= targetWidth) 
                    hi = size; // too big
                else
                    lo = size; // too small
            }
            // Use lo so that we undershoot rather than overshoot
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
            int height = getMeasuredHeight();
            refitText(this.getText().toString(), parentWidth);
            this.setMeasuredDimension(parentWidth, height);
        }
    
        @Override
        protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
            refitText(text.toString(), this.getWidth());
        }
    
        @Override
        protected void onSizeChanged (int w, int h, int oldw, int oldh) {
            if (w != oldw) {
                refitText(this.getText().toString(), w);
          }
        }
    
        //Attributes
        private Paint mTestPaint;
    }
    
    0 讨论(0)
  • 2020-11-22 05:44

    I've been working on improving the excellent solution from speedplane, and came up with this. It manages the height, including setting the margin such that the text should be centered correctly vertically.

    This uses the same function to get the width, as it seems to work the best, but it uses a different function to get the height, as the height isn't provided anywhere. There are some corrections that need to be made, but I figured out a way to do that, while looking pleasing to the eye.

    import android.content.Context;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.util.AttributeSet;
    import android.util.TypedValue;
    import android.widget.TextView;
    
    public class FontFitTextView extends TextView {
    
        public FontFitTextView(Context context) {
            super(context);
            initialize();
        }
    
        public FontFitTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initialize();
        }
    
        private void initialize() {
            mTestPaint = new Paint();
            mTestPaint.set(this.getPaint());
    
            //max size defaults to the initially specified text size unless it is too small
        }
    
        /* Re size the font so the specified text fits in the text box
         * assuming the text box is the specified width.
         */
        private void refitText(String text, int textWidth,int textHeight) 
        { 
            if (textWidth <= 0)
                return;
            int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom();
            float hi = Math.min(targetHeight,100);
            float lo = 2;
            final float threshold = 0.5f; // How close we have to be
    
            Rect bounds = new Rect();
    
            mTestPaint.set(this.getPaint());
    
            while((hi - lo) > threshold) {
                float size = (hi+lo)/2;
                mTestPaint.setTextSize(size);
                mTestPaint.getTextBounds(text, 0, text.length(), bounds);
                if((mTestPaint.measureText(text)) >= targetWidth || (1+(2*(size+(float)bounds.top)-bounds.bottom)) >=targetHeight) 
                    hi = size; // too big
                else
                    lo = size; // too small
            }
            // Use lo so that we undershoot rather than overshoot
            this.setTextSize(TypedValue.COMPLEX_UNIT_PX,(float) lo);
    
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
            int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
            int height = getMeasuredHeight();
            refitText(this.getText().toString(), parentWidth,height);
            this.setMeasuredDimension(parentWidth, height);
        }
    
        @Override
        protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
            refitText(text.toString(), this.getWidth(),this.getHeight());
        }
    
        @Override
        protected void onSizeChanged (int w, int h, int oldw, int oldh) {
    
            if (w != oldw) {
                refitText(this.getText().toString(), w,h);
            }
        }
    
        //Attributes
        private Paint mTestPaint;
    }
    
    0 讨论(0)
  • 2020-11-22 05:45

    I've written a class that extends TextView and does this. It just uses measureText as you suggest. Basically it has a maximum text size and minimum text size (which can be changed) and it just runs through the sizes between them in decrements of 1 until it finds the biggest one that will fit. Not particularly elegant, but I don't know of any other way.

    Here is the code:

    import android.content.Context;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class FontFitTextView extends TextView {
    
        public FontFitTextView(Context context) {
            super(context);
            initialise();
        }
    
        public FontFitTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initialise();
        }
    
        private void initialise() {
            testPaint = new Paint();
            testPaint.set(this.getPaint());
            //max size defaults to the intially specified text size unless it is too small
            maxTextSize = this.getTextSize();
            if (maxTextSize < 11) {
                maxTextSize = 20;
            }
            minTextSize = 10;
        }
    
        /* Re size the font so the specified text fits in the text box
         * assuming the text box is the specified width.
         */
        private void refitText(String text, int textWidth) { 
            if (textWidth > 0) {
                int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
                float trySize = maxTextSize;
    
                testPaint.setTextSize(trySize);
                while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) {
                    trySize -= 1;
                    if (trySize <= minTextSize) {
                        trySize = minTextSize;
                        break;
                    }
                    testPaint.setTextSize(trySize);
                }
    
                this.setTextSize(trySize);
            }
        }
    
        @Override
        protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
            refitText(text.toString(), this.getWidth());
        }
    
        @Override
        protected void onSizeChanged (int w, int h, int oldw, int oldh) {
            if (w != oldw) {
                refitText(this.getText().toString(), w);
            }
        }
    
        //Getters and Setters
        public float getMinTextSize() {
            return minTextSize;
        }
    
        public void setMinTextSize(int minTextSize) {
            this.minTextSize = minTextSize;
        }
    
        public float getMaxTextSize() {
            return maxTextSize;
        }
    
        public void setMaxTextSize(int minTextSize) {
            this.maxTextSize = minTextSize;
        }
    
        //Attributes
        private Paint testPaint;
        private float minTextSize;
        private float maxTextSize;
    
    }
    
    0 讨论(0)
  • 2020-11-22 05:45

    Here is my solution which works on emulator and phones but not very well on Eclipse layout editor. It's inspired from kilaka's code but the size of the text is not obtained from the Paint but from measuring the TextView itself calling measure(0, 0).

    The Java class :

    public class FontFitTextView extends TextView
    {
        private static final float THRESHOLD = 0.5f;
    
        private enum Mode { Width, Height, Both, None }
    
        private int minTextSize = 1;
        private int maxTextSize = 1000;
    
        private Mode mode = Mode.None;
        private boolean inComputation;
        private int widthMeasureSpec;
        private int heightMeasureSpec;
    
        public FontFitTextView(Context context) {
                super(context);
        }
    
        public FontFitTextView(Context context, AttributeSet attrs) {
                this(context, attrs, 0);
        }
    
        public FontFitTextView(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
    
                TypedArray tAttrs = context.obtainStyledAttributes(attrs, R.styleable.FontFitTextView, defStyle, 0);
                maxTextSize = tAttrs.getDimensionPixelSize(R.styleable.FontFitTextView_maxTextSize, maxTextSize);
                minTextSize = tAttrs.getDimensionPixelSize(R.styleable.FontFitTextView_minTextSize, minTextSize);
                tAttrs.recycle();
        }
    
        private void resizeText() {
                if (getWidth() <= 0 || getHeight() <= 0)
                        return;
                if(mode == Mode.None)
                        return;
    
                final int targetWidth = getWidth();
                final int targetHeight = getHeight();
    
                inComputation = true;
                float higherSize = maxTextSize;
                float lowerSize = minTextSize;
                float textSize = getTextSize();
                while(higherSize - lowerSize > THRESHOLD) {
                        textSize = (higherSize + lowerSize) / 2;
                        if (isTooBig(textSize, targetWidth, targetHeight)) {
                                higherSize = textSize; 
                        } else {
                                lowerSize = textSize;
                        }
                }
                setTextSize(TypedValue.COMPLEX_UNIT_PX, lowerSize);
                measure(widthMeasureSpec, heightMeasureSpec);
                inComputation = false;
        }
    
        private boolean isTooBig(float textSize, int targetWidth, int targetHeight) {
                setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
                measure(0, 0);
                if(mode == Mode.Both)
                        return getMeasuredWidth() >= targetWidth || getMeasuredHeight() >= targetHeight;
                if(mode == Mode.Width)
                        return getMeasuredWidth() >= targetWidth;
                else
                        return getMeasuredHeight() >= targetHeight;
        }
    
        private Mode getMode(int widthMeasureSpec, int heightMeasureSpec) {
                int widthMode = MeasureSpec.getMode(widthMeasureSpec);
                int heightMode = MeasureSpec.getMode(heightMeasureSpec);
                if(widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY)
                        return Mode.Both;
                if(widthMode == MeasureSpec.EXACTLY)
                        return Mode.Width;
                if(heightMode == MeasureSpec.EXACTLY)
                        return Mode.Height;
                return Mode.None;
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                if(!inComputation) {
                        this.widthMeasureSpec = widthMeasureSpec;
                        this.heightMeasureSpec = heightMeasureSpec;
                        mode = getMode(widthMeasureSpec, heightMeasureSpec);
                        resizeText();
                }
        }
    
        protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
                resizeText();
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
                if (w != oldw || h != oldh)
                        resizeText();
        }
    
        public int getMinTextSize() {
                return minTextSize;
        }
    
        public void setMinTextSize(int minTextSize) {
                this.minTextSize = minTextSize;
                resizeText();
        }
    
        public int getMaxTextSize() {
                return maxTextSize;
        }
    
        public void setMaxTextSize(int maxTextSize) {
                this.maxTextSize = maxTextSize;
                resizeText();
        }
    }
    

    The XML attribute file :

    <resources>
        <declare-styleable name="FontFitTextView">
            <attr name="minTextSize" format="dimension" />
            <attr name="maxTextSize" format="dimension" />
        </declare-styleable>
    </resources>
    

    Check my github for the latest version of this class. I hope it can be useful for someone. If a bug is found or if the code needs explaination, feel free to open an issue on Github.

    0 讨论(0)
  • 2020-11-22 05:47

    I found the following to work nicely for me. It doesn't loop and accounts for both height and width. Note that it is important to specify the PX unit when calling setTextSize on the view. Thanks to the tip in a previous post for this!

    Paint paint = adjustTextSize(getPaint(), numChars, maxWidth, maxHeight);
    setTextSize(TypedValue.COMPLEX_UNIT_PX,paint.getTextSize());
    

    Here is the routine I use, passing in the getPaint() from the view. A 10 character string with a 'wide' character is used to estimate the width independent from the actual string.

    private static final String text10="OOOOOOOOOO";
    public static Paint adjustTextSize(Paint paint, int numCharacters, int widthPixels, int heightPixels) {
        float width = paint.measureText(text10)*numCharacters/text10.length();
        float newSize = (int)((widthPixels/width)*paint.getTextSize());
        paint.setTextSize(newSize);
    
        // remeasure with font size near our desired result
        width = paint.measureText(text10)*numCharacters/text10.length();
        newSize = (int)((widthPixels/width)*paint.getTextSize());
        paint.setTextSize(newSize);
    
        // Check height constraints
        FontMetricsInt metrics = paint.getFontMetricsInt();
        float textHeight = metrics.descent-metrics.ascent;
        if (textHeight > heightPixels) {
            newSize = (int)(newSize * (heightPixels/textHeight));
            paint.setTextSize(newSize);
        }
    
        return paint;
    }
    
    0 讨论(0)
  • 2020-11-22 05:48
    /* get your context */
    Context c = getActivity().getApplicationContext();
    
    LinearLayout l = new LinearLayout(c);
    l.setOrientation(LinearLayout.VERTICAL);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0);
    
    l.setLayoutParams(params);
    l.setBackgroundResource(R.drawable.border);
    
    TextView tv=new TextView(c);
    tv.setText(" your text here");
    
    /* set typeface if needed */
    Typeface tf = Typeface.createFromAsset(c.getAssets(),"fonts/VERDANA.TTF");  
    tv.setTypeface(tf);
    
    // LayoutParams lp = new LayoutParams();
    
    tv.setTextColor(Color.parseColor("#282828"));
    
    tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
    //  tv.setLayoutParams(lp);
    
    tv.setTextSize(20);
    l.addView(tv);
    
    return l;
    
    0 讨论(0)
提交回复
热议问题