1.在res/layout目录下新建Title bar的xml文件,如:title_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_dark"
android:gravity="fill_horizontal"
android:orientation="horizontal" >
<TextView
android:id="@+id/title_bar"
android:paddingLeft="10dp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_dark"
android:text="@string/app_name"
android:textColor="@android:color/holo_blue_light" />
</LinearLayout>
2.在res/values目录下修改styles.xml文件内容如下:
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="CustomTheme" parent="android:Theme">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="android:windowTitleBackgroundStyle">@null</item>
</style>
<!-- Application theme. -->
<style name="CustomTheme" parent="android:Theme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
其中
<item name="android:windowTitleBackgroundStyle">@null</item>
为设置Title Bar的背景填充整个屏幕,否则默认的会留出一些空白区域来。
3.修改AndroidManifest.xml中的android:theme="@style/CustomTheme"
4.在onCreate函数中修改如下
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_login);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
其中
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
和
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
为设置Title的相关代码,且顺序不能改变!
Android4.0后设置Tilte bar可能会报错:android.util.AndroidRuntimeException: You cannot combine custom titles with other title features 解决办法删除res/values-v11和res/values-v14目录下的文件