Reducing text size in textview if the view is covered by another view or is off screen

57 views Asked by At

I am trying to make sure the text is completely visible within a fixed height view. If the textview's height is taller than the view it is in, the text size will need to shrink. Someone told me to use Paint and measure the text. I'm not sure how I am supposed to check if the view is out it's parents view or being covered by another view.

                ViewTreeObserver vto = mTextView.getViewTreeObserver();
                vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        ViewTreeObserver obs = mTextView.getViewTreeObserver();
                        obs.removeGlobalOnLayoutListener(this);
                        Paint paint = mTextView.getPaint();
                        float measurment = paint.measureText(mTextView.getText().toString()); 

                        //What to do!? 
                        }
                    });
1

There are 1 answers

0
Eli Rising On

View, the superclass of TextView, has a getHeight() function which will measure the pixel size. See also TextView.getLineHeight() to return the height, in pixels, of a single line of text, and getLineCount() for the number of lines the TextView has.

I would caution against your method. It is much easier (/saner) to use different layout densities, instead of programmatically adjusting your layouts between devices. It's a bit annoying to set up, but I would say that it's way easier to set up your layouts once in a GUI preview than have to redo math and switch back and forth between running and testing.