Android实现ExpandableTextView可扩展TextView

介绍

在应用开发中,总会遇到一些类似于公告,说明等长文本的TextView,但是为了排版美观等因素,我们通常是要隐藏后半部的文本,只显示部分文字,然后在尾部会提供用户一个扩展/收缩的按钮,使得文本框可以在需要的时候扩展开来查看全文,这就需要实现一个ExpendableTextView,类似于ExpendableList。

原理

1、开始时使用android:lines来设置TextView的行数,点击按钮之后,解除限制。

2、使用android:ellipsize来设置文本的省略位置。

3、要记得设置android:layout_height="wrap_content",不然固定了高度,就没法实现了。

实现

main.xml布局

<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="com.example.appupdate.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:lines="3"
        android:text="我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告我是说明我是公告"
        android:textColor="@android:color/black" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="点击展开" />

</RelativeLayout>

核心代码

   private TextView textView1;
    private Button button1;
    private boolean isExpend = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1 = (TextView) findViewById(R.id.textView1);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isExpend) {
                    // 复原
                    textView1.setMinLines(0);
                    textView1.setMaxLines(Integer.MAX_VALUE);
                    button1.setText("点击收缩");
                    isExpend=true;
                } else {
                    textView1.setLines(3);
                    button1.setText("点击展开");
                    isExpend=false;
                }
            }
        });
    }

运行之后看起来是这样的

找个时候好好重构一下,做一个自定义控件,实现真正意义上的ExpendableTextView

原文地址:https://www.cnblogs.com/leestar54/p/4246068.html