編輯:關於 Android 程式設計
刷朋友圈動態時常看到這種設計:內容長的只顯示前幾行,想讀完整再點擊展開。這樣整頁列表的高度比較平均,不會被個別長文佔掉半個螢幕。文章列表也是同樣思路。本文整理三種實作方式:自定義文字展開、ExpandableListView,以及帶折紙動畫的 FoldingLayout。
列表本身用 ListView 即可,難點在「動態內容」這個子控制項,核心是如何把高度變化做成動畫。先複習四個 TextView 方法:
若預設顯示四行,初始高度就是 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 完成後才觸發。
嵌套列表的場景不少:好友分組與好友、訂單與訂單內商品、郵件夾與郵件等。Android 自帶的 ExpandableListView 直接可用。
ExpandableListAdapter 並不繼承自其他適配器,是獨立的一套。常用的有 getGroupCount、getChildrenCount、getGroupView、getChildView、isChildSelectable。
這是 ExpandableListView 最常見的困惑。要讓子項正常回應點擊,必須同時滿足:
第三點最容易被忽略,尤其是子項裡放了 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); // 預設展開第一個郵件夾
ExpandableListView 對一般場景夠用,但視覺風格偏樸素。若想要展開收合時有點特效,就得自己來。FoldingLayout 是一個開源的折疊式版面元件,能做出像折紙一樣的展開與收合動畫。
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)再依序展開,可以避開首次測量尚未完成的問題。
Android 熱插拔事件全解析:從 Kernel uevent 一路走到「設定-儲存空間」
一、先看全局:一張圖理清熱插拔事件鏈路 Android 的熱插拔能力,本質上是一條從內核到應用層的單向事件流。內核發現設備變化後廣播 uevent,Vold 守護進程接手
Android Menu 按鍵功能
Android 應用可透過選單按鍵彈出選項。開發者可覆寫 onCreateOptionsMenu 加入選單項目,再覆寫 onOptionsItemSelected 處理點
Android 屬性動畫進階實作:XML 動畫、LayoutTransition 與 View.animate()
屬性動畫的基本概念 屬性動畫的重點在於「改變物件的屬性值」,而不是只替換畫面。常見的 API 包含 ValueAnimator、ObjectAnimator 與 Anim
Android DrawerLayout 抽屜菜單實作:從版面結構到側滑互動
DrawerLayout 同樣來自 V4 支援庫,直接繼承 ViewGroup,本質上是一個容器。它把「漢堡選單」這個互動模式變成一行 XML 就能搞定的事,是近幾年最常