android开发之定制标题栏 --- 附源码
在开发上个应用 话费速查 的时候,需要修改标题栏的样式,但是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>
?
好了,现在可以看看效果了:
?
?
源码下载地址:点击这里
1 楼 aswang 2012-04-12 奇怪,iteye上传的附件都不显示了,怎么回事? 2 楼 mvpstevenlin 2012-04-20 写得很好啊!!!