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

Android 開發筆記(一百):三種折疊式列表實作與動畫處理

編輯:關於 Android 程式設計

刷朋友圈動態時常看到這種設計:內容長的只顯示前幾行,想讀完整再點擊展開。這樣整頁列表的高度比較平均,不會被個別長文佔掉半個螢幕。文章列表也是同樣思路。本文整理三種實作方式:自定義文字展開、ExpandableListView,以及帶折紙動畫的 FoldingLayout。

動態展開:掌握高度與動畫

列表本身用 ListView 即可,難點在「動態內容」這個子控制項,核心是如何把高度變化做成動畫。先複習四個 TextView 方法:

  • getHeight:取得目前顯示高度。
  • setHeight:設定顯示高度。
  • getLineHeight:取得單行文字高度。
  • getLineCount:取得文字總行數。

若預設顯示四行,初始高度就是 getLineHeight * 4;展開後要顯示全部,高度為 getLineHeight * getLineCount。有了起點與終點,剩下的就是一個把高度從起點推到終點的動畫。

做法是在點擊時建立一個匿名 Animation,於 applyTransformation 中依 interpolatedTime 對高度做線性插值:

private final OnClickListener mOnClickListener = new View.OnClickListener() {
    boolean isExpand;

    @Override
    public void onClick(View v) {
        tv_expand.setText(isExpand ? "查看全文" : "收起關注");
        isExpand = !isExpand;
        tv_content.clearAnimation();

        final int startValue = tv_content.getHeight();
        final int deltaValue;
        if (isExpand) {
            deltaValue = tv_content.getLineHeight() * tv_content.getLineCount() - startValue;
        } else {
            deltaValue = tv_content.getLineHeight() * maxLine - startValue;
        }

        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                tv_content.setHeight((int) (startValue + deltaValue * interpolatedTime));
            }
        };
        animation.setDuration(300);
        tv_content.startAnimation(animation);
    }
};

這裡有個細節值得注意:每次點擊都要先 clearAnimation,否則連續快速點擊會讓多個動畫同時改高度,出現跳動。另外,getLineCount 在版面尚未完成時可能回傳 0,若遇到高度算成 0 的情況,應先確認是否已在 layout 完成後才觸發。

ExpandableListView:系統現成的嵌套列表

嵌套列表的場景不少:好友分組與好友、訂單與訂單內商品、郵件夾與郵件等。Android 自帶的 ExpandableListView 直接可用。

常用方法

  • setAdapter:設定 ExpandableListAdapter 型別的適配器。
  • expandGroup / collapseGroup:展開或收合指定分組。
  • isGroupExpanded:判斷分組是否展開。
  • setSelectedGroup / setSelectedChild:設定選中的分組或子項。
  • setGroupIndicator / setChildIndicator:設定分組與子項的指示圖示。

四個監聽器

  • 分組展開:OnGroupExpandListener → setOnGroupExpandListener → onGroupExpand
  • 分組收合:OnGroupCollapseListener → setOnGroupCollapseListener → onGroupCollapse
  • 分組點擊:OnGroupClickListener → setOnGroupClickListener → onGroupClick
  • 子項點擊:OnChildClickListener → setOnChildClickListener → onChildClick

適配器要重寫的方法

ExpandableListAdapter 並不繼承自其他適配器,是獨立的一套。常用的有 getGroupCount、getChildrenCount、getGroupView、getChildView、isChildSelectable。

子項點不動?檢查這三件事

這是 ExpandableListView 最常見的困惑。要讓子項正常回應點擊,必須同時滿足:

  1. 適配器的 isChildSelectable 回傳 true;
  2. 已呼叫 setOnChildClickListener 並重寫 onChildClick;
  3. 子項版面中若有 Button、EditText 這類預設搶焦點的元件,要透過 setFocusable(false) 與 setFocusableInTouchMode(false) 解除焦點佔用。

第三點最容易被忽略,尤其是子項裡放了 CheckBox 的時候。

以郵箱為例的實作

資料結構是「郵件夾 → 郵件列表」兩層,對應 getGroup 與 getChild。這裡讓適配器本身實作 OnGroupClickListener 與 OnChildClickListener,Activity 只要各註冊一次即可。

public class CustomExpandAdapter implements ExpandableListAdapter,
        OnGroupClickListener, OnChildClickListener {

    private final LayoutInflater mInflater;
    private final Context mContext;
    private final ArrayList<MailBox> mBoxList;

    public CustomExpandAdapter(Context context, ArrayList<MailBox> boxList) {
        mInflater = LayoutInflater.from(context);
        mContext = context;
        mBoxList = boxList;
    }

    @Override
    public int getGroupCount() {
        return mBoxList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mBoxList.get(groupPosition).mail_list.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mBoxList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mBoxList.get(groupPosition).mail_list.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) { return groupPosition; }

    @Override
    public long getChildId(int groupPosition, int childPosition) { return childPosition; }

    @Override
    public boolean hasStableIds() { return false; }

    // 分組視圖,沿用 convertView 避免重複 inflate
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        ViewHolderBox holder;
        if (convertView == null) {
            holder = new ViewHolderBox();
            convertView = mInflater.inflate(R.layout.list_box, null);
            holder.iv_box = convertView.findViewById(R.id.iv_box);
            holder.tv_box = convertView.findViewById(R.id.tv_box);
            holder.tv_count = convertView.findViewById(R.id.tv_count);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolderBox) convertView.getTag();
        }
        MailBox box = mBoxList.get(groupPosition);
        holder.iv_box.setImageResource(box.box_icon);
        holder.tv_box.setText(box.box_title);
        holder.tv_count.setText(box.mail_list.size() + "封郵件");
        return convertView;
    }

    // 子項視圖,CheckBox 必須解除焦點佔用
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parent) {
        ViewHolderMail holder;
        if (convertView == null) {
            holder = new ViewHolderMail();
            convertView = mInflater.inflate(R.layout.list_mail, null);
            holder.ck_mail = convertView.findViewById(R.id.ck_mail);
            holder.tv_date = convertView.findViewById(R.id.tv_date);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolderMail) convertView.getTag();
        }
        final MailItem item = mBoxList.get(groupPosition).mail_list.get(childPosition);
        holder.ck_mail.setFocusable(false);
        holder.ck_mail.setFocusableInTouchMode(false);
        holder.ck_mail.setText(item.mail_title);
        holder.ck_mail.setOnCheckedChangeListener((buttonView, isChecked) -> {
            String desc = String.format("您點擊了%s的郵件,標題是%s",
                    mBoxList.get(groupPosition).box_title, item.mail_title);
            Toast.makeText(mContext, desc, Toast.LENGTH_LONG).show();
        });
        holder.tv_date.setText(item.mail_date);
        return convertView;
    }

    // 子項要能回應點擊,這裡必須回傳 true
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean areAllItemsEnabled() { return true; }

    @Override
    public boolean isEmpty() { return false; }

    @Override
    public void onGroupExpanded(int groupPosition) { }

    @Override
    public void onGroupCollapsed(int groupPosition) { }

    @Override
    public long getCombinedChildId(long groupId, long childId) { return 0; }

    @Override
    public long getCombinedGroupId(long groupId) { return 0; }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) { }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) { }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
                               int groupPosition, int childPosition, long id) {
        ViewHolderMail holder = (ViewHolderMail) v.getTag();
        holder.ck_mail.setChecked(!holder.ck_mail.isChecked());
        return true;
    }

    // 回傳 true 會吃掉分組點擊,導致無法展開子列表
    @Override
    public boolean onGroupClick(ExpandableListView parent, View v,
                               int groupPosition, long id) {
        String desc = String.format("您點擊了%s", mBoxList.get(groupPosition).box_title);
        Toast.makeText(mContext, desc, Toast.LENGTH_LONG).show();
        return false;
    }

    static class ViewHolderBox {
        ImageView iv_box;
        TextView tv_box;
        TextView tv_count;
    }

    static class ViewHolderMail {
        CheckBox ck_mail;
        TextView tv_date;
    }
}

onGroupClick 的回傳值很容易寫錯:回傳 true 代表事件已被消費,分組就不會展開。要在提示的同時保留展開行為,就必須回傳 false。

ExpandableListView elvList = findViewById(R.id.elv_list);
ArrayList<MailBox> boxList = new ArrayList<>();
boxList.add(new MailBox(R.drawable.mail_folder_inbox, "收件箱", getRecvMail()));
boxList.add(new MailBox(R.drawable.mail_folder_outbox, "發件箱", getSentMail()));
boxList.add(new MailBox(R.drawable.mail_folder_draft, "草稿箱", getDraftMail()));
boxList.add(new MailBox(R.drawable.mail_folder_recycle, "廢件箱", getRecycleMail()));

CustomExpandAdapter adapter = new CustomExpandAdapter(this, boxList);
elvList.setAdapter(adapter);
elvList.setOnChildClickListener(adapter);
elvList.setOnGroupClickListener(adapter);
elvList.expandGroup(0);   // 預設展開第一個郵件夾

FoldingLayout:加上折紙動畫

ExpandableListView 對一般場景夠用,但視覺風格偏樸素。若想要展開收合時有點特效,就得自己來。FoldingLayout 是一個開源的折疊式版面元件,能做出像折紙一樣的展開與收合動畫。

常用方法

  • setFoldFactor:折疊因子,0 為收合、1 為展開。
  • setOrientation:折疊方向,VERTICAL 或 HORIZONTAL。
  • setNumberOfFolds:折疊頁數。

折疊監聽

OnFoldListener(透過 setFoldListener 設定)有三個回呼:onStartFold 在開始折疊時觸發、onFoldingState 在折疊狀態變化時持續觸發、onEndFold 在結束時觸發。

實作要點

這個元件最麻煩的不是動畫本身,而是折疊過程中版面佔用的高度必須同步補償,否則下方內容會在動畫期間跳動。做法是在 onFoldingState 中依 foldFactor 動態調整下一個區塊的 topMargin。

private void handleAnimation(final View bar, final FoldingLayout foldingLayout,
                             View parent, final View nextParent) {
    foldingLayout.setVisibility(View.VISIBLE);
    final ImageView arrow = parent.findViewWithTag(TAG_ARROW);

    foldingLayout.setFoldListener(new OnFoldListener() {
        @Override
        public void onStartFold(float foldFactor) {
            bar.setClickable(true);
            arrow.setBackgroundResource(R.drawable.service_arrow_up);
            resetMarginToTop(foldingLayout, foldFactor, nextParent);
        }

        @Override
        public void onFoldingState(float foldFactor, float foldDrawHeight) {
            bar.setClickable(false);   // 動畫期間禁止重複點擊
            resetMarginToTop(foldingLayout, foldFactor, nextParent);
        }

        @Override
        public void onEndFold(float foldFactor) {
            bar.setClickable(true);
            arrow.setBackgroundResource(R.drawable.service_arrow_down);
            resetMarginToTop(foldingLayout, foldFactor, nextParent);
        }
    });

    animateFold(foldingLayout, FOLD_ANIMATION_DURATION);
}

private void resetMarginToTop(View view, float foldFactor, View nextParent) {
    LinearLayout.LayoutParams lp =
            (LinearLayout.LayoutParams) nextParent.getLayoutParams();
    lp.topMargin = (int) (-view.getMeasuredHeight() * foldFactor)
            + MetricsUtil.dip2px(FoldingActivity.this, 10);
    nextParent.setLayoutParams(lp);
}

public void animateFold(FoldingLayout foldLayout, int duration) {
    float foldFactor = foldLayout.getFoldFactor();
    ObjectAnimator animator = ObjectAnimator.ofFloat(foldLayout, "foldFactor",
            foldFactor, foldFactor > 0 ? 0 : 1);
    animator.setRepeatMode(ValueAnimator.REVERSE);
    animator.setRepeatCount(0);
    animator.setDuration(duration);
    animator.setInterpolator(new AccelerateInterpolator());
    animator.start();
}

折疊區塊初始化時記得先設為 INVISIBLE 並把 foldFactor 歸零,等版面完成後(這裡用 Handler.postDelayed)再依序展開,可以避開首次測量尚未完成的問題。

三個方案怎麼選

  • 只是單段文字要能展開收合:自己寫個高度動畫即可,成本最低。
  • 標準的兩層嵌套列表:直接用 ExpandableListView,記住子項焦點那三個檢查點。
  • 需要視覺效果或折紙風格:用 FoldingLayout,並處理好折疊期間的 margin 補償。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved