textview.getLineCount always 0 in android

前端 未结 6 1564
执笔经年
执笔经年 2020-11-30 04:28

I\'m trying to dynamically resize my textview but getlinecount() method always returns me 0 even after settext() and invalidate(). I\'m using the following code:



        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 05:21

    In order to fix this issue apply the following lines:

    textView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (textView.getLineCount() > 1) {
                textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    });
    

    The OnGlobalLayoutListener will be called after every change to the TextView (after measuring it, drawing it, ..). Here you can catch changes to your TextView before it'll be drawn to the screen and do whatever you need with it.

    The last line in the code is to remove the listener, it's important since we don't want to continue catching each layout change.

提交回复
热议问题