Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Measure Size of View before rendering

I have a TextView that displays text that changes and run time. I want to use the View.getLineCount() method to see how many lines the TextView takes up and do different functions accordingly. The problem is I need to determine the number of lines the TextView takes up in the same method that needs to know how many line it takes up. I have tried calling View.invalidate() in between the two calls but that hasn't seemed to fix anything. I would like to measure the number of lines without rendering the view if possible but if I have to render it I would be open to doing that as well. Let me know if this is not specific enough and I will try to be more specific. Thanks!

like image 287
Corey Alexander Avatar asked Nov 14 '22 08:11

Corey Alexander


1 Answers

This can actually be a really complex problem in Android. If you need to know at the time you set the text (ie before the view is rendered or near being rendered), you're only real option is to use StaticLayout. If you can wait until near render time, you can use a viewTreeObserver:

yourTextView.getViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout(){
        yourTextView.getLineCount();
    }
}

onGlobalLayout can be called multiple times and sometimes (for whatever reason) I've found that views aren't actually laid out yet, so you should do some logging and see if you can find a way to make sure that whatever result you get actually makes sense (ie a line count > 0).

StaticLayouts are a more complicated alternative that should be able to give you the size of your view and number of lines. They can require some tweaking to get to work properly, and make sure you use the paint from the view you're trying to measure:

yourTextView.setText(newText);
//the last boolean should be true if you're using padding on your view
StaticLayout measure = new StaticLayout(yourTextView.getText(), yourTextView.getPaint(), 
    maxAvailableWidthForYourTextView, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false)

int numberOfLines = measure.getLineCount();

If you're willing to (or already have) subclassed TextView, you can override onSizeChanged or onMeasure and try to get the number of lines there. Again, like with the view tree observer, sometimes those can be called before your view has actually been measured, so you may have to check to make sure whatever value you get in those methods make sense.

like image 67
Sam Judd Avatar answered Dec 26 '22 05:12

Sam Judd