Android: measuring the size of a view before rendering

I have a TextView that displays text that changes and starts time. I want to use the View.getLineCount () method to see how many lines a TextView occupies and performs various functions, respectively. The problem is that I need to determine the number of lines that TextView uses in the same method, which should know how many lines it takes. I tried calling View.invalidate () between two calls, but this does not seem to fix anything. I would like to measure the number of rows without rendering the view, if possible, but if I do, I will be ready for that too. Let me know if this is not enough and I will try to be more specific. Thank you

+5
source share
1 answer

This is really a really difficult problem in Android. If you need to know at the time you set the text (i.e. before visualizing the view or next to the visualization), you can only use StaticLayout. If you can wait until rendering, you can use viewTreeObserver:

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

onGlobalLayout can be called several times, and sometimes (for some reason) I found that the views are not laid out yet, so you have to make some notes and see if you can find a way to make sure that any result you get is actually meaningful ( i.e. the number of rows> 0).

StaticLayouts - , . , , :

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();

( ) TextView, onSizeChanged onMeasure . , , , , , , , , , .

+1

All Articles