1.创建自己的标题栏样式,代码如下:
<resources> <!-- 自定义的标题栏 --> <style name="CustomWindowTitleBackground"> <item name="android:background">#836FFF</item> </style> <style name="CustomTitleBar" parent="android:Theme"> <item name="android:windowTitleSize">32dp</item> <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item> <!--设置titlebar的背景--> </style> <style name="styleName"> <item name="android:orientation">horizontal</item> </style> </resources>
2.新建一个layout文件,如mycustomtitle.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="45dp" android:background="@color/blue" > <ImageButton android:id="@+id/share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:src="@drawable/share" android:background="@color/blue" android:contentDescription="@string/share" android:paddingRight="5dp"/> <ImageButton android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:contentDescription="@string/back" android:src="@drawable/back" android:background="@color/blue" android:padding="5dp" /> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:gravity="center" android:text="@string/title" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout>
效果如图所示
3.在AndroidManifest.xml中,做如下修改
<application android:allowBackup="true" android:icon="@drawable/app" android:label="@string/app_name" android:theme="@style/CustomTitleBar" >
4.在Java中调用该标题的方法,如下:注意代码的顺序,很重要
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.activity); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.mycustomtitle); }