[英]Android TextView in one line
下面是我的代码。 我需要在这个片段上获得像这样的结果:
什么时候是短字符串:
1 line: ABC (123)
什么时候是长字符串:
1 line: ABC ABC ABC ABC ABC...(123)
有什么帮助吗?
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/id1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:ellipsize="end"
android:maxLines="1"
android:visibility="visible"
android:text="ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC"
android:textSize="@dimen/text_size_form"/>
<TextView
android:id="@+id/id2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:ellipsize="end"
android:maxLines="1"
android:text="123"
android:textSize="@dimen/text_size_form"/>
</LinearLayout>
您还可以使用如下所示的 RelativeLayout 和属性..
这是示例代码..试试这个。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/id1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/id2"
android:ellipsize="end"
android:singleLine="true"
android:text="ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC"
android:textStyle="bold"
android:visibility="visible" />
<TextView
android:id="@+id/id2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:ellipsize="end"
android:maxLines="1"
android:text="123"
android:visibility="visible" />
</RelativeLayout>
输出如下图所示。
在您的 Textview 中添加此属性 android:singleLine="true"
您可以检查字符串长度,如果它比特定长度长,那么您可以根据需要显示它。
前任。 你想要的最大长度是 20
if (str.length()>20) {
str = str.substring(0, 20)+"...";
}
使用下面的代码
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/id1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:ellipsize="end"
android:maxLines="1"
android:visibility="visible"
android:text="ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC"
android:textSize="@dimen/text_size_form"/>
<TextView
android:id="@+id/id2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:ellipsize="end"
android:maxLines="1"
android:text="123"
android:layout_marginLeft="-3dp"
android:textSize="@dimen/text_size_form"/>
</LinearLayout>
尝试-
String s = "ABC ABC ABC ABC";
if(s.split(" ").length>1)
{
s = s.split(" ")[0]+" ("+s.split(" ").length+")";
}
textView.setText(s);
只需将其添加到您的 xml 中
android:ellipsize="middle"
android:singleLine="true"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.