編輯:關於 Android 程式設計
上一篇介紹了 Material Design 中的各種動畫效果,搭配第一篇的內容,已經足夠寫出不錯的 UI 了。這次來看幾個實用度很高、但官方沒有直接提供的元件。
先附上學習資源:
https://github.com/traex/ExpandableLayout
https://githubonepiece.github.io/2015/11/26/Material-Design-Palette/
https://www.fx114.net/qa-26-168872.aspx
https://blog.csdn.net/jdsjlzx/article/details/41441083/
https://github.com/Flipboard/bottomsheet
這個元件非常常用,但 Android 自帶的 ExpandableListView 用起來頗不順手,而且必須繼承它自帶的 Adapter,程式碼寫起來綁手綁腳。在 GitHub 上看到 ExpandableLayout 之後,才明白差距可以這麼大。效果大家都見過——QQ 的好友列表展開就是這一類。
使用方式很簡單,先在 build.gradle 加入依賴:
dependencies {
compile 'com.github.traex.expandablelayout:library:1.2.2'
}
接著就能在 XML 中使用 ExpandableLayout、ExpandableLayoutItem、ExpandableLayoutListView 三個控制項。
ExpandableLayout 需要指定 head layout 與 content layout:
<com.andexert.expandablelayout.library.ExpandableLayout
android:id="@+id/expandableLayout"
android:layout_height="match_parent"
android:layout_width="match_parent"
expandable:headerLayout="@layout/view_header"
expandable:contentLayout="@layout/view_content"
xmlns:expandable="https://schemas.android.com/apk/res-auto">
</com.andexert.expandablelayout.library.ExpandableLayout>
自己寫好這兩個 XML 檔即可,效果就是點擊 view_header 之後 view_content 展開顯示。當然這個效果自己也能實作(放兩個控制項,一個隱藏,點擊時切換可見性),但用現成元件省去不少細節處理。
ExpandableLayoutListView 同樣可以直接放進 XML:
<com.andexert.expandablelayout.library.ExpandableLayoutListView
android:id="@+id/expandableLayoutList"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:expandable="https://schemas.android.com/apk/res-auto">
</com.andexert.expandablelayout.library.ExpandableLayoutListView>
而填充這個清單則使用 ExpandableLayoutItem:
<com.andexert.expandablelayout.library.ExpandableLayoutItem
android:id="@+id/expandableLayoutItem"
android:layout_height="match_parent"
android:layout_width="match_parent"
expandable:headerLayout="@layout/view_header"
expandable:contentLayout="@layout/view_content"
xmlns:expandable="https://schemas.android.com/apk/res-auto">
</com.andexert.expandablelayout.library.ExpandableLayoutItem>
Java 端幾乎不需要做什麼,只要照一般方式為 ListView 寫 Adapter 就好,剩下的事交給元件。這裡僅做簡介,細節可到 GitHub 上查。
Material Design 很強調「圖片配色、文字顏色與主題色彼此協調」。Android Lollipop 提供的 Palette 類別就是為了解決這件事:它能從一張圖片中提取主要顏色。例如一張海景照,Palette 大概會告訴你主色偏藍。
先加入依賴:
compile 'com.android.support:palette-v7:23.0.0'
Palette 共有四種產生方式,其中前兩種已被官方標記為不建議使用,但了解一下可以避免看到舊程式碼時霧裡看花。
同步方式:
Palette p = Palette.generate(bitmap); Palette p = Palette.generate(bitmap, size); // 指定調色板大小
非同步方式:
// 內部使用 AsyncTask,簡便但不一定最佳(存在執行緒切換)
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// palette 即生成的調色板,預設大小 16
}
});
// 指定調色板大小為 24
Palette.generateAsync(bitmap, 24, new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) { }
});
Palette.Builder builder = Palette.from(bitmap);
builder.generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) { }
});
// 也可以寫得更精簡
Palette.from(bitmap).generate(new PaletteAsyncListener() {
public void onGenerated(Palette p) { }
});
調色板數值越大,產生抽色所花的時間越長;數值越小,取到的顏色資訊越少。實務上建議依圖片類型決定,預設是 16。
有了 Palette 物件後,可以嘗試取得六種色板:
Palette.Swatch s1 = palette.getVibrantSwatch(); // 鮮明色 Palette.Swatch s2 = palette.getDarkVibrantSwatch(); // 鮮明的暗色 Palette.Swatch s3 = palette.getLightVibrantSwatch(); // 鮮明的亮色 Palette.Swatch s4 = palette.getMutedSwatch(); // 柔和色 Palette.Swatch s5 = palette.getDarkMutedSwatch(); // 柔和的暗色 Palette.Swatch s6 = palette.getLightMutedSwatch(); // 柔和的亮色
每個 Swatch 提供五項資訊:
getPopulation() // 該色代表的像素數量 getRgb() // 顏色的 RGB 值 getHsl() // 顏色的 HSL 值 getBodyTextColor() // 適合疊在此色上的內文顏色 getTitleTextColor() // 適合疊在此色上的標題顏色
使用範例:
Palette.Swatch swatch = palette.getVibrantSwatch();
if (swatch != null) {
titleView.setBackgroundColor(swatch.getRgb());
titleView.setTextColor(swatch.getTitleTextColor());
}
務必判斷 swatch 是否為 null。若調色板找不到符合條件的色,會回傳 null,不做檢查就會拿到空指標例外。也可以用帶預設值的版本:
tv1.setBackgroundColor(palette.getVibrantColor(0x999933)); tv2.setBackgroundColor(palette.getDarkVibrantColor(0x999933)); tv3.setBackgroundColor(palette.getLightVibrantColor(0x999933)); tv4.setBackgroundColor(palette.getMutedColor(0x999933)); tv5.setBackgroundColor(palette.getDarkMutedColor(0x999933)); tv6.setBackgroundColor(palette.getLightMutedColor(0x999933));
這樣即使取不到色,也會退回預設的 0x999933。

照上面的程式碼試一試就能得到類似效果。若想參考 Palette 在完整 App 中的應用,可以看看「Android Material Design 之 Toolbar 與 Palette 實踐」(https://blog.csdn.net/jdsjlzx/article/details/41441083/ ),作者也附上了源碼。
這個看起來就很帥。知乎的分享面板大家都用過——從底部彈出、一排可選的分享目標,往下拉整個畫面還會跟著移動。效果這麼好,程式碼應該很難吧?其實不然,因為總有人會幫你把元件包好。這裡用的是 Flipboard 的 bottomsheet。

先在 build.gradle 加入依賴:
dependencies {
compile 'com.flipboard:bottomsheet-core:1.5.0'
compile 'com.flipboard:bottomsheet-commons:1.5.0' // optional
}
那個 optional 的意思是:如果你只需要 bottom sheet 顯示一個畫面,可以不要 commons;若需要內建的分享面板、選單等能力,就把它加上。
版面配置也要稍作調整。原本可能是這樣:
<LinearLayout android:id="@+id/root"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<View android:id="@+id/view1"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</LinearLayout>
要在其中使用 bottom sheet,外層需包成 BottomSheetLayout:
<com.flipboard.bottomsheet.BottomSheetLayout
android:id="@+id/bottomsheet"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout android:id="@+id/root"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<View android:id="@+id/view1"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</LinearLayout>
</com.flipboard.bottomsheet.BottomSheetLayout>
最簡單的用法:只顯示一個畫面,Java 端兩行搞定。
BottomSheetLayout bottomSheet = (BottomSheetLayout) findViewById(R.id.bottomsheet);
bottomSheet.showWithSheetView(
LayoutInflater.from(context).inflate(R.layout.my_sheet_layout, bottomSheet, false));
其中 R.layout.my_sheet_layout 就是你要顯示的畫面。
第二種:知乎式的分享面板,可以點擊項目執行對應操作。

版面配置同上,只是不需要另外準備顯示用的 XML。程式碼如下:
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "分享內容");
intent.setType("text/plain");
IntentPickerSheetView intentPickerSheet = new IntentPickerSheetView(
MainActivity.this, intent, "分享到",
new IntentPickerSheetView.OnIntentPickedListener() {
@Override
public void onIntentPicked(IntentPickerSheetView.ActivityInfo activityInfo) {
bottomsheet.dismissSheet();
startActivity(activityInfo.getConcreteIntent(intent));
}
});
// 自行加入項目:圖示、標題與點擊後要開啟的 Activity
List<IntentPickerSheetView.ActivityInfo> activityInfo = new ArrayList<>();
Drawable d1 = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, null);
activityInfo.add(new IntentPickerSheetView.ActivityInfo(d1, "自訂項目一",
MainActivity.this, MainActivity.class));
Drawable d2 = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, null);
activityInfo.add(new IntentPickerSheetView.ActivityInfo(d2, "自訂項目二",
MainActivity.this, Main2Activity.class));
intentPickerSheet.setMixins(activityInfo);
bottomsheet.showWithSheetView(intentPickerSheet);
}
});
幾點補充:想做成知乎那種分享效果,把 Intent.ACTION_SEND 換成對應的分享 Intent 即可。下半段程式碼是我們自己往面板裡塞的項目,透過 setMixins(List<ActivityInfo>) 加入圖示、標題與點擊行為,可以照同樣方式加多項。具體行為建議自己跑一次、並看過作者的方法與參數設計再調整。
最後:自訂 Bottom Sheet。這時要用 MenuSheetView,寫法也不難。先建立 menu 資料夾(若已有就跳過),新增 activity_menu.xml:
<menu xmlns:android="https://schemas.android.com/apk/res/android">
<item android:icon="@mipmap/ic_launcher" android:title="@string/document" />
<item android:icon="@mipmap/ic_launcher" android:title="@string/spreadsheet" />
<item android:icon="@mipmap/ic_launcher" android:title="@string/folder" />
<item android:id="@+id/menu_subheader" android:title="子標題">
<menu>
<item android:id="@+id/navigation_sub_item_1"
android:icon="@mipmap/ic_launcher" android:title="@string/upload_photos" />
<item android:id="@+id/navigation_sub_item_2"
android:icon="@mipmap/ic_launcher" android:title="@string/use_camera" />
</menu>
</item>
<item android:id="@+id/reopen"
android:icon="@mipmap/ic_launcher" android:title="@string/reopen" />
</menu>
接著在 Activity 中為選單項目掛上點擊事件:
MenuSheetView menuSheetView = new MenuSheetView(
MenuActivity.this, MenuSheetView.MenuType.LIST, "建立...",
new MenuSheetView.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MenuActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
if (bottomSheetLayout.isSheetShowing()) {
bottomSheetLayout.dismissSheet();
}
return true;
}
});
menuSheetView.inflateMenu(R.menu.activity_menu);
bottomSheetLayout.showWithSheetView(menuSheetView);
MenuSheetView.MenuType 除了 LIST 還有 GRID,一個是清單一個是格狀,前面的 GIF 已經把兩種效果都展示了。
官方 sample 裡還有兩種玩法:一是 ImagePicker,把相簿圖片放進 bottom sheet;二是直接在 bottom sheet 中放一個 Fragment。既然連 Fragment 都能塞,可玩性就非常高了。不過實際 App 中最常見的还是前兩種,後兩種等真正需要時再深入。
Android 開發核心知識:Activity 與 Fragment 完整解析
Activity 與 Fragment 是 Android 介面開發的兩根支柱。本文從生命週期、通訊方式、資料傳遞到 Fragment 的動態操作,做一次系統性梳理。
Android 沉浸式狀態欄實戰:從原理到 API 21 完全透明
前言 這裡不打算爭論「沉浸式」這個詞用得準不準確,大家聽得懂就好。本文整理自實際專案中的經驗,歡迎一起探討。由於實習期間長期處於高強度加班狀態,一直沒時間做總結,直到某天
Android 百日程序:Fragment 動態管理與生命週期
之前寫過 Fragment 的使用,Fragment 可以靜態聲明,也可以在運行時動態載入。這一章進一步看看如何動態更換 Fragment,以及 Fragment 生命週
Android 仿微信標籤功能:FlowLayout 自動換行與標籤增刪
微信收藏中的標籤功能需要支援新增、刪除與自動換行。FlowLayout 是常見解法,它會依子 View 寬度與容器寬度決定是否換行,適合動態標籤、關鍵字與分類項目。