How do I tell if my textview has been ellipsized?

前端 未结 14 1672
天涯浪人
天涯浪人 2020-11-30 19:31

I have a multi-line TextView that has android:ellipsize=\"end\" set. I would like to know, however, if the string I place in there is actually too

14条回答
  •  情书的邮戳
    2020-11-30 20:04

    textView.getLayout is the way to go but the problem with that is that it returns null if layout is not prepared. Use the below solution.

     ViewTreeObserver vto = textview.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
               Layout l = textview.getLayout();
               if ( l != null){
                  int lines = l.getLineCount();
                  if ( lines > 0)
                      if ( l.getEllipsisCount(lines-1) > 0)
                        Log.d(TAG, "Text is ellipsized");
               }  
            }
        });
    

    Code snippet for removing the listener (source):

    mLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            scrollToGridPos(getCenterPoint(), false);
            mLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);        
        }
    });
    

提交回复
热议问题