Program Tip

내 textview가 생략되었는지 어떻게 알 수 있습니까?

programtip 2020. 11. 3. 18:53
반응형

내 textview가 생략되었는지 어떻게 알 수 있습니까?


설정된 여러 줄 TextView이 있습니다 android:ellipsize="end". 그러나 내가 거기에 넣은 문자열이 실제로 너무 긴지 알고 싶습니다 (전체 문자열이 페이지의 다른 곳에 표시되도록 할 수 있습니다).

TextView.length()문자열의 대략적인 길이가 맞는지 사용 하고 찾을 수 있지만 여러 줄이기 때문에 줄 TextView을 감을 때 핸들이 있으므로 항상 작동하지는 않습니다.

어떤 아이디어?


의 레이아웃을 가져 TextView오고 줄당 줄임표 수를 확인할 수 있습니다. 끝 줄임표의 경우 다음과 같이 마지막 줄을 확인하는 것으로 충분합니다.

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");
}

이것은 레이아웃 단계 후에 만 ​​작동합니다. 그렇지 않으면 반환 된 레이아웃이 null이되므로 코드의 적절한 위치에서 호출하십시오.


textView.getLayout은 갈 길이지만 문제는 레이아웃이 준비되지 않은 경우 null을 반환한다는 것입니다. 아래 솔루션을 사용하십시오.

 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");
           }  
        }
    });

이 질문에 대한 가장 쉬운 해결책은 다음 코드입니다.

String text = "some looooong text";
textView.setText(text);
boolean isEllipsize = !((textView.getLayout().getText().toString()).equalsIgnoreCase(text));

이 코드는 XML에서 TextView가 다음을 설정한다고 가정합니다. maxLineCount:)


public int getEllipsisCount (int line) :

생략 할 문자 수를 반환하거나 생략 할 문자가 없으면 0을 반환합니다.

따라서 간단히 전화하십시오.

int lineCount = textview1.getLineCount();

if(textview1.getLayout().getEllipsisCount(lineCount) > 0) {
   // Do anything here..
}

레이아웃이 설정되기 전에 getLayout ()을 호출 할 수 없으므로 다음을 사용하십시오.

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");
       }  
    }
});

마지막으로 더 이상 필요하지 않을 removeOnGlobalLayoutListener 를 제거하는 것을 잊지 마십시오.


이것은 나에게 일했습니다.

textView.post(new Runnable() {
                        @Override
                        public void run() {
                            if (textView.getLineCount() > 1) {
                                //do something
                            }
                        }
                    });

lateinit var toggleMoreButton: Runnable
toggleMoreButton = Runnable {
  if(reviewTextView.layout == null) { // wait while layout become available
       reviewTextView.post(toggleMoreButton) 
       return@Runnable
  }
  readMoreButton.visibility = if(reviewTextView.layout.text.toString() != comment) View.VISIBLE else View.GONE
}
reviewTextView.post(toggleMoreButton)

몇 가지 일반적인 경우입니다.

  1. 'reviewTextView'의 주석
  2. 일부 기준에 따라 댓글이 접힐 수 있습니다.
  3. 댓글이 접힌 경우 'readMoreButton'버튼이 표시됩니다.

그것은 나를 위해 일하고있다

if (l != null) {
    int lines = l.getLineCount();
     if (lines > 0) {
     for (int i = 0; i < lines; i++) {
     if (l.getEllipsisCount(i) > 0) {
      ellipsize = true;
      break;
     }
    }
   }
  }

Really work so, for example, to pass full data to dialog from item of RecyclerView:

holder.subInfo.post(new Runnable() {
                @Override
                public void run() {
                    Layout l = holder.subInfo.getLayout();
                    if (l != null) {
                        final int count = l.getLineCount();
                        if (count >= 3) {
                            holder.subInfo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    final int c = holder.subInfo.getLineCount();
                                    if (c >= 3) {
                                        onClickToShowInfoDialog.showDialog(holder.title.getText().toString(), holder.subInfo.getText().toString());
                                    }
                                }
                            });
                        }
                    }
                }
            });

The Kotlin way:

textView.post {
   if (textView.lineCount > MAX_LINES_COLLAPSED) {
   // text is not fully displayed
   }
}

Actually View.post() is executed after the view has been rendered and will run the function provided


Using getEllipsisCount won't work with text that has empty lines within it. I used the following code to make it work :

message.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {

            if(m.isEllipsized == -1) {
                Layout l = message.getLayout();
                if (message.getLineCount() > 5) {
                    m.isEllipsized = 1;
                    message.setMaxLines(5);
                    return false;
                } else {
                    m.isEllipsized = 0;
                }
            }
            return true;
        }
    });

Make sure not to set a maxLineCount in your XML. Then you can check for the lineCount in your code and if it is greater than a certain number, you can return false to cancel the drawing of the TextView and set the line count as well as a flag to save whether the text view is too long or not. The text view will draw again with the correct line count and you will know whether its ellipsized or not with the flag.

You can then use the isEllipsized flag to do whatever you require.


create a method inside your TextViewUtils class

public static boolean isEllipsized(String newValue, String oldValue) {
    return !((newValue).equals(oldValue));
}

call this method when it's required eg:

        if (TextViewUtils.isEllipsized(textviewDescription.getLayout().getText().toString(), yourModelObject.getDescription()))
            holder.viewMore.setVisibility(View.VISIBLE);//show view more option
        else
            holder.viewMore.setVisibility(View.GONE);//hide 

but textView.getLayout() can't call before the view(layout) set.

참고URL : https://stackoverflow.com/questions/4005933/how-do-i-tell-if-my-textview-has-been-ellipsized

반응형