在Android自定义标题栏,步骤很简单:
1. 在onCreate方法中声明如下代码:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.id.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom.title_bar);
2. 在layout中定义如下文件:
custom_title_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:drawableLeft="@drawable/arrow"
android:drawablePadding="@dimen/custom_title_bar_arrow_padding"
android:layout_marginLeft="@dimen/custom_title_bar_text_margin_left"
android:text="@string/back"
android:textSize="@dimen/activity_login_button_text_size"
android:textColor="@color/activity_login_button_color"
android:visibility="gone"/>
</LinearLayout>
setTheme(R.style.CustomTitleBarTheme); //声明标题栏,注意这一句的位置
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.cus_title_bar); //注意顺序
<style name="CustomTitleBarTheme" parent="android:Theme.Light">
<!--定义标题栏的高度-->
<item name="android:windowTitleSize">@dimen/custom_title_bar_height</item>
<!--定义标题栏的背景-->
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
<style name="WindowTitleBackground">
<item name="android:background">@drawable/custom_title_bar</item>
</style>