在listView的item中或者是特殊的业务需求中,会要求TextView的内容不完全显示,只有通过一个指定的操作后才显示所有的,比如说一个按钮或者是其它的什么控件。
要想实现这个效果并不难,只要控制好TextView的行数就行。文章中介绍了两种实现方法,一种是给button添加Flag,另一种是给button添加Tag,两种方法都可以,具体说不上哪种更好,哪种适合用哪种。
第一种方法的布局,注意TextView中必须加上android:ellipsize和android:maxLines这两条属性,不然的话效果出不来:
<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/text1"
android:layout_marginTop="10dp" >
<TextView
android:id="@+id/text2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉四谛法邝健廉" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:text="下拉" />
</RelativeLayout>
</RelativeLayout></span>
接下来就可以在类中控制这个TextView显示或者隐藏了。
<span style="font-size:14px;"> button.setOnClickListener(new OnClickListener() {
Boolean flag = true;
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (flag) {
flag = false;
text.setEllipsize(null);// 展开
text.setSingleLine(flag);
button.setText("隐藏");
} else {
flag = true;
text.setMaxLines(2);// 收缩
button.setText("显示");
// text.setEllipsize(TruncateAt.END);
}
}
});</span>
或者可以在Button中添加一个Tag
<span style="font-size:14px;"><Button
android:id="@+id/item_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="@drawable/packup"
android:tag="true" /></span>
<span style="font-size:14px;"> viewItme.item_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Boolean flag = Boolean.valueOf((String) viewItme.item_btn.getTag()) ;
if (flag) {
// 展开
viewItme.item_btn.setTag("false");
viewItme.inspecttext_tv.setEllipsize(null);
viewItme.inspecttype_tv.setEllipsize(null);
viewItme.item_describe.setEllipsize(null);
viewItme.item_describe.setMaxLines(10);
viewItme.item_btn.setBackgroundResource(R.drawable.unfloddd);
} else {
// 收缩
viewItme.item_btn.setTag("true");
viewItme.item_describe.setMaxLines(1);
viewItme.item_btn.setBackgroundResource(R.drawable.packup);
}
}
});</span>