program story

TextView의 문자 수를 제한 할 수 있습니까?

inputbox 2020. 11. 7. 09:29
반응형

TextView의 문자 수를 제한 할 수 있습니까?


내가 지금 가지고있는 것은 TextView 요소의 ListView입니다. 각 TextView 요소는 텍스트를 표시합니다 (텍스트 길이는 12 단어에서 100+까지 다양 함). 내가 원하는 것은 이러한 TextView가 텍스트의 일부를 표시하도록 만드는 것입니다 (20 단어 또는 대략 170 자).

TextView를 고정 된 문자 수로 제한하는 방법은 무엇입니까?


여기에 예가 있습니다. maxLength 속성으로 크기를 제한하고 maxLines 속성으로 한 줄로 제한 한 다음 ellipsize = end를 사용하여 잘린 줄 끝에 자동으로 "..."를 추가합니다.

<TextView 
    android:id="@+id/secondLineTextView" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:maxLines="1" 
    android:maxLength="10" 
    android:ellipsize="end"/>

TextView에서 아래 코드 사용

 android:maxLength="65"

즐겨...


xml 솔루션에 관심이 없다면 다음과 같이 할 수 있습니다.

String s="Hello world";
Textview someTextView;
someTextView.setText(getSafeSubstring(s, 5));
//the text of someTextView will be Hello

...

public String getSafeSubstring(String s, int maxLength){
  if(!TextUtils.isEmpty(s)){
    if(s.length() >= maxLength){
      return s.substring(0, maxLength);
    }
  }
  return s;
}

TextView 클래스 http://developer.android.com/reference/android/widget/TextView.html#setEllipsize(android.text.TextUtils.TruncateAt) 의 setEllipsize 메서드를 사용할 수 있습니다.

추가 된 TextUtil 클래스의 상수로 http://developer.android.com/reference/android/text/TextUtils.TruncateAt.html


maxEms속성을 사용하여이 작업을 수행했습니다 .

 <TextView
    android:ellipsize="end"
    android:maxEms="10"/>

언급 된 바와 같이 https://stackoverflow.com/a/6165470/1818089https://stackoverflow.com/a/6239007/1818089 사용

android:minEms="2"

위에서 언급 한 목표를 달성하기에 충분해야합니다.


TextView 클래스를 확장하고 setText () 함수를 덮어 쓸 수 있습니다. 이 기능에서는 텍스트 길이 또는 단어 cound를 확인합니다.

참고 URL : https://stackoverflow.com/questions/9149846/can-i-limit-textviews-number-of-characters

반응형