Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 ExpandableTextView:長文字折疊與展開的完整實作

編輯:關於 Android 程式設計

做社群、新聞或商品詳情類的介面時,常常會碰到一段文字太長、把整個版面撐開的情況。理想的做法是預設只顯示前面幾行,尾端用省略符號收尾,使用者點一下再把全文展開。本文就示範如何自定義一個 ExpandableTextView 來完成這樣的互動。

一、實作思路

核心邏輯其實很單純:繼承 TextView,內部同時保存「原始全文」與「截斷後的文字」兩份內容,再用一個 boolean 旗標決定目前該顯示哪一份。掛上 OnClickListener 切換旗標,折疊與展開就完成了。

二、自定義控制項程式碼

public class ExpandableTextView extends TextView {

    private static final int DEFAULT_TRIM_LENGTH = 200;
    private static final String ELLIPSIS = ".....";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(
                R.styleable.ExpandableTextView);
        trimLength = typedArray.getInt(
                R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }

    private void setText() {
        super.setText(getDisplayableText(), bufferType);
    }

    private CharSequence getDisplayableText() {
        return trim ? trimmedText : originalText;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        bufferType = type;
        setText();
    }

    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
            return new SpannableStringBuilder(originalText, 0, trimLength + 1)
                    .append(ELLIPSIS);
        }
        return originalText;
    }

    public CharSequence getOriginalText() {
        return originalText;
    }

    public void setTrimLength(int trimLength) {
        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);
        setText();
    }

    public int getTrimLength() {
        return trimLength;
    }
}

三、宣告自定義屬性

因為我們希望折疊長度可以從 XML 指定,所以必須先在 res/values/attr.xml 中宣告 styleable:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpandableTextView">
        <attr name="trimLength" format="integer" />
    </declare-styleable>
</resources>

四、在版面檔中引用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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=".ExpandableTextActivity" >

    <com.example.expandtextviewdemo.ExpandableTextView
        android:id="@+id/lorem_ipsum"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</RelativeLayout>

五、在 Activity 中填入測試文字

public class ExpandableTextActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expandable_text);

        String yourText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
                + "Ut volutpat interdum interdum. Nulla laoreet lacus diam, vitae "
                + "sodales sapien commodo faucibus. Vestibulum et feugiat enim. Donec "
                + "semper mi et euismod tempor. Sed sodales eleifend mi id varius. Nam "
                + "et ornare enim, sit amet gravida sapien. Quisque gravida et enim vel "
                + "volutpat. Vivamus egestas ut felis a blandit.";

        ExpandableTextView expandableTextView =
                (ExpandableTextView) findViewById(R.id.lorem_ipsum);
        expandableTextView.setText(yourText);
    }
}

六、幾個實務上要注意的地方

這個實作把折疊狀態綁在點擊事件上,寫法簡潔,但如果要更貼近產品需求,通常還需要補強幾點:

  • 「展開/收起」最好有明確的文字提示(例如「展開全文」「收起」),單靠省略符號使用者不一定會發現可以點。
  • 如果希望依照行數折疊而不是字數,可以改用 TextView.getLayout().getLineCount() 搭配 Layout 來判斷,或在 API 26 以上直接使用系統提供的 TextView.setMaxLines() 搭配 collapseActionCode。
  • 折疊狀態會在 Activity 重建時遺失,記得在 onSaveInstanceState 中保存。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved