編輯:關於 Android 程式設計
PreferenceActivity 完全使用系統預定義的佈局,因此不能像其它窗口那樣簡單地自定義。現在我們需要為它加一個自定義標題,比如像其它窗口一樣加一個統一的 topbar,假設這個 topbar 的佈局是 title.xml。
Android 提供了自定義標題欄的方法,可以簡單實現:
@Override
protected void onCreate(Bundle savedInstanceState) {
final boolean isCustom = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_setting);
addPreferencesFromResource(R.xml.setting_preference);
if (isCustom)
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
}
但在 Android 4.0 上會提示:
You cannot combine custom titles with other title features
網上提供了很多複雜辦法來解決,但關鍵是——在 PreferenceActivity 上總是失敗。
在 xml/preference.xml 佈局文件下加入:
<Preference android:layout="@layout/title" android:key="app_info"/>
這樣可以實現「偽標題欄」。這種方法的缺點是佈局無法鋪滿整個窗口,兩側會出現白邊,非常不好看。
查閱資料後發現,PreferenceActivity 其實是支持完全自定義佈局的,只需保證佈局中包含一個 id 為 android:id="@android:id/list" 的 ListView 即可。在調用 addPreferencesFromResource() 後,preference 列表會自動加載到這個 ListView 中,而標題佈局只需簡單地放在 ListView 之上即可。
下面是成功的佈局,效果非常令人滿意:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/bg_color" >
<include android:id="@+id/title" layout="@layout/title"></include>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="@color/transparent"
android:fadingEdgeLength="0dp"
android:scrollbars="none"
android:fadingEdge="none"
android:listSelector="#00000000" />
</LinearLayout>
這種方法還會帶來額外的好處:可以自由自定義 preference 列表的背景色等外觀,讓設置界面與整個應用的風格保持統一。
Android 6.0 應用啟動全流程源碼深度剖析
以下分析基於 API 23(Android 6.0)。想真正搞懂一個 App 是怎麼從桌面圖標被點亮、一路走到 Activity 呈現在眼前的,那就得潛進源碼,順著調用鏈
ListView 源碼深度解析:復用機制全流程
前言 雖然 RecyclerView 問世已久、ListView 看似過時,但它有許多優秀的思想仍值得細細品味。提到 ListView,大家第一反應就是復用機制。這裡不再
Android Intent 完全指南:顯式、隱式與數據回傳
Intent 是 Android 各組件之間交互的核心手段。它既能說明「我想做什麼動作」,也能在組件之間搬運數據,常見用途包括啟動 Activity、啟動 Service
全面介紹 Android 的 MVVM 框架 —— Data Binding 數據綁定
本教程總結了跟隨 Data Binding 官方指南學習過程中的一些實踐經驗,同時修正了官方教程裡的若干錯誤。每個知識點都配有對應源碼,力求做到理論與實踐相結合。 Dat