Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android PreferenceActivity 自定義標題的簡單方法

編輯:關於 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 上總是失敗。

二、自定義一個 preference 佈局並作為第一個配置項

在 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 列表的背景色等外觀,讓設置界面與整個應用的風格保持統一。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved