Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

FadingActionBar 使用心得:三個必踩的相容性地雷

先給結論:這個庫對目前主流的 AppCompat 版 ActionBar 與 Toolbar 幾乎沒有支援,不建議新專案採用。以下記錄我實際試用的過程,供仍在維護舊專案的人參考。

專案地址:https://github.com/ManuelPeinado/FadingActionBar

前面試錯花了半天,整理結論又耗掉兩小時,希望這篇能幫你省下這段時間。

四個相容性陷阱

  1. 不要用 v7 的 ActionBarActivity 作為 parent,否則會直接丟出 NullPointerException。
  2. 繼承 Activity 雖然能避開空指針,但拿不到透明效果——只要 theme 用了 v7 的 AppCompat 就是空指針。總之凡是與 AppCompat 沾邊的組合,這裡都行不通。
  3. 避開 Holo 的 DarkActionBar 與 NoActionBar:前者會顯示白色 ActionBar 而且文字也是白色,幾乎看不見;後者照樣空指針。
  4. 建議直接找別的庫。若日後找不到合適方案,自己實作一個簡版可能反而更快。

引用方式就不贅述,GitHub 上有 gradle 依賴寫法。

基本用法

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FadingActionBarHelper helper = new FadingActionBarHelper()
            .actionBarBackground(R.drawable.ab_background)
            .headerLayout(R.layout.header)
            .contentLayout(R.layout.activity_listview);
    setContentView(helper.createView(this));
    helper.initActionBar(this);

    ListView listView = (ListView) findViewById(android.R.id.list);
    ArrayList<String> items = loadItems(R.raw.nyc_sites);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, items);
    listView.setAdapter(adapter);
}

三個參數的意義

  • actionBarBackground:下拉後 ActionBar 的背景。官方文件建議使用 9-patch 圖,才能正確處理可拉伸區域。
  • headerLayout:下方圖片顯示區的布局。這個區域的尺寸必須嚴格控制,若與下方 ListView 之間出現大片空白,通常就是 header 布局被引用後佔據了非預期的大小,在 Android Studio 的預覽中可以直接看出問題。
  • contentLayout:ListView 等內容的位置,這裡有個硬性要求:
<ListView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

id 必須是 @android:id/list 這個系統 id,不能自訂,因為庫內部是靠它來定位清單的。這一點若沒注意到,會呈現列表完全不顯示的現象,而且不一定報錯,相當難查。

最終效果與限制

依上述配置可以做出「header 隨滾動淡出、ActionBar 背景漸顯」的視覺效果,但無法實現 ActionBar 初始全透明那一段,這是本庫在當前版本下的先天限制。若你的設計稿要求完整透明漸變,建議改用 Toolbar 搭配自訂的 collapsing 方案,會省下大量相容性折騰。

Copyright © Linux教程網 All Rights Reserved