限制TextView的长度

22 android

可能重复:
限制Android中EditText的文本长度

我是Activity上的textView,它是根据它从JSON响应接收的参数显示的,我需要将它限制为仅12个字符.

<TextView
    android:id="@+id/textViewName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/includeheadersetting"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="20dp"
    android:gravity="center"
    android:text="Name"
    android:textColor="#000000"
    android:textStyle="bold" />
Run Code Online (Sandbox Code Playgroud)

Nir*_*tel 74

使用android:maxLength="12"限制文本长度

 <TextView
            android:id="@+id/textViewName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/includeheadersetting"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:text="Name"
            android:maxLength="12"
            android:textColor="#000000"
            android:textStyle="bold" />
Run Code Online (Sandbox Code Playgroud)

您还可以使用其他属性,如下所示:

android:ellipsize="end"
android:maxLines="1"
Run Code Online (Sandbox Code Playgroud)

使用此属性"..."将添加到文本的末尾,如下所示:

"你好,怎么样......"而不是"你好,你好吗?"


Vip*_*hah 7

一般来说,只包括android:maxLength不被认为是好主意。

使用 maxLength 属性,然后使用android:ellipsize="marquee"将“...”自动添加到已被截断的任何行的末尾。

<TextView 
    android:id="@+id/txtView" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:maxLines="1" 
    android:maxLength="10" 
    android:ellipsize="marquee"/>
Run Code Online (Sandbox Code Playgroud)