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

仿朋友圈「全文/收起」:RecyclerView 動態文字展開的實作思路

編輯:關於 Android 程式設計

社交類 App 的動態流有個共同難題:貼文長度天差地遠。若全部展開,短貼文下方會留一大片空白;若一律截斷,想看完的人又得點進詳情頁。正解是「超過一定行數才顯示全文」——短的直接鋪滿,長的折疊起來附一個「全文」連結。本文示範如何用 RecyclerView 做到,並處理捲動回收後的狀態保持。

核心邏輯:先量,再決定要不要摺

關鍵在於 ViewTreeObserver.OnPreDrawListener。文字實際渲染後,可以透過 TextView.getLineCount() 得知它佔了幾行。若超過門檻(這裡設為 3 行),就設 setMaxLines(3) 並顯示「全文」;否則隱藏連結,讓它自然鋪滿。

但這裡有個 RecyclerView 特有的陷阱:項目會被回收重用。同一個 ViewHolder 會被綁定到不同 position 的資料上,若不做狀態記錄,使用者展開某一則後往下捲,回來時狀態就錯亂了。解法是用一個 SparseArray 記錄每個 position 的展開狀態。

item 版面配置

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin">

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_gravity="center_vertical"
         android:orientation="horizontal">

         <TextView
             android:id="@+id/tv_hend"
             android:layout_width="40dp"
             android:layout_height="40dp"
             android:layout_marginRight="16dp"
             android:background="@drawable/circle"
             android:gravity="center"
             android:textColor="@android:color/white"
             android:textSize="14sp" />

         <TextView
             android:id="@+id/tv_name"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="丁先森"
             android:textColor="@android:color/black"
             android:textSize="14sp" />
     </LinearLayout>

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginLeft="56dp"
         android:orientation="vertical"
         android:paddingBottom="8dp">

         <TextView
             android:id="@+id/tv_content"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginBottom="8dp"
             android:ellipsize="end"
             android:textColor="@android:color/black"
             android:textSize="14sp" />

         <TextView
             android:id="@+id/tv_expand_or_collapse"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="全文"
             android:textColor="@color/colorPrimaryDark"
             android:textSize="14sp" />
     </LinearLayout>

     <View
         android:layout_width="match_parent"
         android:layout_height="0.5dp"
         android:layout_marginLeft="56dp"
         android:alpha="0.12"
         android:background="@android:color/black" />
</LinearLayout> 

資料來源

實務上這裡會改為讀取資料庫或解析 JSON,為了聚焦在展開邏輯,範例用固定陣列:

 package com.example.friendzhanshou;

 /** 2017/2/10 */
 public class Util {

     private static String[] nameArray = new String[]{"Windows", "Mac", "Linux"};

     private static String[] contentArray = new String[]{
             "在動作類影片中,只要發生混亂,那麼絕對就有槍戰。現在的技術越來越發達," +
             "電影或電視中的特效也做的越來越逼真……(此處為長文本示例)" +
             "1、「老實說,比我想像中的感覺要輕很多。」\n" +
             "2、「被子彈打到的感覺就像是一直有人拿針扎你一樣。」\n" +
             "3、「那種感覺用疼痛兩個字已經不足以形容了。」\n" +
             "4、「當時我以為是被蜜蜂螫了。」\n" +
             "5、「直到血流出来才意識到。」",
             "GNOME or KDE desktop\n processor with support for AMD Virtualization"
     };

     /** 依下標循環取得內容 */
     public static String getContent(int position) {
         return contentArray[position % contentArray.length];
     }

     /** 依下標循環取得名稱 */
     public static String getName(int position) {
         return nameArray[position % nameArray.length];
     }
 } 

Adapter:狀態記錄是重點

 package com.example.friendzhanshou;

 import android.app.Activity;
 import android.support.v7.widget.RecyclerView;
 import android.util.SparseArray;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ViewTreeObserver;
 import android.widget.TextView;

 /** 2017/2/10 */
 public class TextListAdapter extends RecyclerView.Adapter<TextListAdapter.TextHolder> {

     private static final int MAX_LINE_COUNT = 3;
     private static final int STATE_UNKNOWN = -1;
     private static final int STATE_NOT_OVERFLOW = 1; // 行數未超過限制
     private static final int STATE_COLLAPSED = 2;    // 已折疊
     private static final int STATE_EXPANDED = 3;     // 已展開

     private Activity mContent;
     /** 記錄每個 position 的展開狀態,應對 RecyclerView 的回收重用 */
     private SparseArray<Integer> mTextStateList;

     public TextListAdapter(Activity context) {
         mContent = context;
         mTextStateList = new SparseArray<>();
     }

     @Override
     public TextHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         return new TextHolder(mContent.getLayoutInflater()
                 .inflate(R.layout.item_text_list, parent, false));
     }

     @Override
     public void onBindViewHolder(final TextHolder holder, final int position) {
         holder.hend.setText(String.valueOf(position + 1));
         holder.name.setText(Util.getName(position));

         int state = mTextStateList.get(position, STATE_UNKNOWN);

         if (state == STATE_UNKNOWN) {
             // 第一次綁定:等版面配置完成後才能取得實際行數
             holder.content.getViewTreeObserver().addOnPreDrawListener(
                     new ViewTreeObserver.OnPreDrawListener() {
                 @Override
                 public boolean onPreDraw() {
                     // 這個回呼可能被呼叫多次,取得行數後務必移除監聽
                     holder.content.getViewTreeObserver().removeOnPreDrawListener(this);
                     if (holder.content.getLineCount() > MAX_LINE_COUNT) {
                         holder.content.setMaxLines(MAX_LINE_COUNT);
                         holder.expandOrCollapse.setVisibility(View.VISIBLE);
                         holder.expandOrCollapse.setText("全文");
                         mTextStateList.put(position, STATE_COLLAPSED);
                     } else {
                         holder.expandOrCollapse.setVisibility(View.GONE);
                         mTextStateList.put(position, STATE_NOT_OVERFLOW);
                     }
                     return true;
                 }
             });
             holder.content.setMaxLines(Integer.MAX_VALUE);
             holder.content.setText(Util.getContent(position));
         } else {
             // 已記錄過狀態,直接套用,不必重新量測
             switch (state) {
                 case STATE_NOT_OVERFLOW:
                     holder.expandOrCollapse.setVisibility(View.GONE);
                     break;
                 case STATE_COLLAPSED:
                     holder.content.setMaxLines(MAX_LINE_COUNT);
                     holder.expandOrCollapse.setVisibility(View.VISIBLE);
                     holder.expandOrCollapse.setText("全文");
                     break;
                 case STATE_EXPANDED:
                     holder.content.setMaxLines(Integer.MAX_VALUE);
                     holder.expandOrCollapse.setVisibility(View.VISIBLE);
                     holder.expandOrCollapse.setText("收起");
                     break;
             }
             holder.content.setText(Util.getContent(position));
         }

         // 全文/收起的切換
         holder.expandOrCollapse.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 int current = mTextStateList.get(position, STATE_UNKNOWN);
                 if (current == STATE_COLLAPSED) {
                     holder.content.setMaxLines(Integer.MAX_VALUE);
                     holder.expandOrCollapse.setText("收起");
                     mTextStateList.put(position, STATE_EXPANDED);
                 } else if (current == STATE_EXPANDED) {
                     holder.content.setMaxLines(MAX_LINE_COUNT);
                     holder.expandOrCollapse.setText("全文");
                     mTextStateList.put(position, STATE_COLLAPSED);
                 }
             }
         });
     }

     @Override
     public int getItemCount() {
         return 15;
     }

     public static class TextHolder extends RecyclerView.ViewHolder {
         TextView hend;
         TextView name;
         TextView content;
         TextView expandOrCollapse;

         TextHolder(View itemView) {
             super(itemView);
             hend = (TextView) itemView.findViewById(R.id.tv_hend);
             name = (TextView) itemView.findViewById(R.id.tv_name);
             content = (TextView) itemView.findViewById(R.id.tv_content);
             expandOrCollapse = (TextView) itemView.findViewById(R.id.tv_expand_or_collapse);
         }
     }
 } 

主版面配置與 Activity

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:id="@+id/activity_main"
     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">

     <android.support.v7.widget.RecyclerView
         android:id="@+id/rv_text_list"
         android:layout_width="match_parent"
         android:layout_height="match_parent" />
</RelativeLayout> 
 package com.example.friendzhanshou;

 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.support.v7.widget.LinearLayoutManager;
 import android.support.v7.widget.RecyclerView;

 public class MainActivity extends AppCompatActivity {

     private RecyclerView mRvTextList;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         mRvTextList = (RecyclerView) findViewById(R.id.rv_text_list);
         mRvTextList.setLayoutManager(
                 new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
         mRvTextList.setAdapter(new TextListAdapter(this));
     }
 } 

三個實務上的改進點

用 position 當 key 會出問題。 一旦資料有新增或刪除,原本 position 對應的狀態就會錯位——使用者展開的貼文,在插入一筆新貼文後會變成另一則的狀態。正式專案應改用資料本身的唯一 id(例如貼文 id)當 key,而不是 position。

OnPreDrawListener 要小心重複註冊。 這個回呼在版面配置過程中可能被呼叫多次。範例中雖已在開頭移除監聽,但如果在快速捲動時同一個 ViewHolder 被反覆綁定,仍可能殘留監聽。更穩妥的做法是把行數判斷移到自訂 TextView 的 onMeasure 之後,或改用 post() 延後一幀執行。

記得加上 View 重用時的狀態重置。 由於 RecyclerView 會回收 ViewHolder,若某個 item 被綁定到「未溢出」的資料上,而它上一次顯示的是「已展開」狀態,就必須在綁定時明確重設 maxLines,否則會殘留前一位的樣子。範例中的 else 分支已處理這點,這也是整個實作最容易漏掉的地方。

另外,若你的貼文內容含有表情符號、@提及或連結需要特殊渲染,建議改用 SpannableString 或自訂 TextView 處理,而不是在這層邏輯裡堆疊。展開/收起的機制本身,與內容如何渲染是兩個獨立的問題,分開處理會清楚得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved