http://aswang.iteye.com/blog/1483904
在開發上個應用 話費速查 的時候,需要修改標題欄的樣式,但是android自身的標題欄是不支持修改樣式的,因此需要通過下面的方式讓android支持自定義標題欄:
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
- setContentView(R.layout.main);
- getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
注意上面的代碼順序不要改變,否則不會有效果。
上面的R.layout.title就是自定義標題欄的佈局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- android:layout_gravity="center_vertical">
- <ImageView
- android:src="@drawable/phone"
- android:contentDescription="@string/desc"
- android:gravity="center_vertical"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"/>
- <TextView android:text="@string/app_name"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginLeft="5dip"
- android:gravity="center_vertical"
- android:textColor="#FFFFFF"
- android:textSize="20sp"/>
- <TextView android:text="@string/use_tips"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginLeft="10dip"
- android:gravity="center_vertical"
- android:textColor="#ABACAC"
- android:textSize="15sp"/>
- </LinearLayout>
但是僅僅這樣,還是不夠的。標題欄的背景顏色和高度還是不能改變,還需要給它定義樣式:
- <?xml version="1.0" encoding="utf-8"?>
- <resources xmlns:android ="http://schemas.android.com/apk/res/android">
- <style name ="CustomWindowTitleBackground">
- <item name ="android:background">#1F497D</item>
- </style>
- <style name="title" parent="android:Theme">
- <item name ="android:windowTitleSize">45dp</item>
- <item name ="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
- </style>
- </resources>
上面樣式文件中的背景顏色 和 標題大小都是可以自己修改的。
最後,將該樣式應用到Main Activity(即啓動Activity):
- <activity
- android:name=".BillQueryActivity"
- android:label="@string/app_name"
- android:theme="@style/title">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
好了,現在可以看看效果了:
源碼下載地址:點擊這裏