先給結論:這個庫對目前主流的 AppCompat 版 ActionBar 與 Toolbar 幾乎沒有支援,不建議新專案採用。以下記錄我實際試用的過程,供仍在維護舊專案的人參考。
專案地址:https://github.com/ManuelPeinado/FadingActionBar
前面試錯花了半天,整理結論又耗掉兩小時,希望這篇能幫你省下這段時間。
引用方式就不贅述,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);
}
<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 方案,會省下大量相容性折騰。