標籤:
自訂標題列在很多的android app中很常見,可以說是一種很有用的UI設計方法。自
己也本著學習的態度,經過一番各種坑,終於實現了,現總結如下:
一:大致流程
1. 對指定的android activity設定自訂佈景主題風格,其中自訂佈景主題風格是關鍵
在android 4.0以上版本中如果使用Theme.Holo或者Theme.Light等,程式會
一直報錯誤-you cannot combine custom title with other feature titles
2. 在對應的Activity中加入代碼
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.mycustomtitle);
3. 在styles.xml使用如下的自訂佈景主題,發現只有使用這個預設主題才不出第一步的
錯誤,真是各種坑啊!
<resources> <style name="WindowTitleBackground" > </style> <style name="MyTheme" parent="android:Theme"> <item name="android:windowTitleSize">60dp</item> <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item> </style></resources>
4. 關鍵技巧,使用RelativeLayout來對齊自訂Title的組件
二:測試MainActivity原始碼
package com.gloomyfish.titledemo;import android.app.Activity;import android.os.Bundle;import android.view.Window;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.mycustomtitle); } }
三:XML資源檔
mycustomtitle.xml的內容
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_gravity="fill_horizontal" android:orientation="horizontal" android:layout_height="fill_parent" > <Button android:id="@+id/header_left_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="5dp" android:layout_centerVertical="true" android:text="back" android:textColor="#000000"/> <TextView android:id="@+id/header_text" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_toRightOf="@+id/header_left_btn" android:layout_toLeftOf="@+id/header_right_btn" android:text="My Title Bar" android:textSize="20sp" android:textStyle="bold" android:textColor="#FFFFFF" android:gravity="center" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:singleLine="true" /> <Button android:id="@+id/header_right_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="5dp" android:layout_centerVertical="true" android:text="next" android:textColor="#000000"/></RelativeLayout>
最後別忘記在androi的manifest設定檔中加上自訂的主題
android:theme="@style/MyTheme"
【Android UI】自訂帶按鈕的標題列