標籤:
介紹
在應用開發中,總會遇到一些類似於公告,說明等長文本的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
Android實現ExpendableTextView可擴充TextView