Android开发中,系统定义的标题栏往往满足不了我们的需求,这时候需要我们DIY自己的标题栏,不说多了直接上代码:
1.创建自定义标题栏布局文件:titleBar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是title" />
</LinearLayout>
2.Activity中onCreate()按照下列顺序添加代码
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);//添加代码1
setContentView(R.layout.layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.titlebar);// 设置自定义标题栏 添加代码2
3.res/value/styles.xml 创建如下样式
4.AndroidManifest.xml Activity中添加样式,覆盖默认样式
android:theme="@style/test"
<!-- 自定义titlebar -->
<!-- titleBar背景颜色 -->
<style name="CustomWindowTitleBackground">
<item name="android:background">@drawable/back</item>
</style>
<!-- titleBar style -->
<style name="test" parent="android:Theme">
<item name="android:windowTitleSize">50dp</item>
<item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
</style>
这样四步就可以了