版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31796651/article/details/79422309
开发中经常会遇到textview内容过多显示两三行后边显示省略号,有时还会需要点击展开全部显示:
效果图是这样的,不会gif图制作,只能上图片
好了直接上代码:
//这是点击的代码
if (isShowDes) {
tvDes.setEllipsize(TextUtils.TruncateAt.END);//收起
tvDes.setLines(3);
tvShowMore.setText("展开");
} else {
tvDes.setEllipsize(null);//展开
tvDes.setSingleLine(false);//这个方法是必须设置的,否则无法展开
tvShowMore.setText("收起");
}
isShowDes = !isShowDes;
<!--xml的代码:主要注意maxLines而不是lines属性,优点是小于3行不至于有很多空白-->
<TextView
android:id="@+id/tv_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_016"
android:layout_marginRight="@dimen/margin_016"
android:layout_marginTop="@dimen/margin_016"
android:ellipsize="end"
android:maxLines="3"
android:textColor="@color/tt_666666"
android:textSize="@dimen/text_size_14" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_show_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="@dimen/margin_012"
android:padding="@dimen/margin_04"
android:text="展开"
android:textColor="@color/tt_yellow"
android:textSize="@dimen/text_size_14" />
</RelativeLayout>
最后还可以在activity中的
onWindowFocusChanged方法处理展开按钮是否显示
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
if (tvDes.getLineCount() < 3) {//获得textview显示行数不要在设置值后直接获取,可能会得到0,因为内容还没完全加载
tvShowMore.setVisibility(View.GONE);
}
}
}
这样就实现了textview内容过多展示问题!