Android 自定义标题栏的实例详解

开发 Android APP 经常会用到自定义标题栏,而有多级页面的情况下还需要给自定义标题栏传递数据。
本文要点:
自定义标题填充不完整
自定义标题栏返回按钮的点击事件
一、代码
这里先介绍一下流程:
1. 创建一个标题栏布局文件 mytitlebar.xml
2. 在style.xml中创建 mytitlestyle 主题
3. 创建类 CustomTitleBar
4. 在需要自定义标题栏的Activity的OnCreate方法中实例化 CustomTitleBar
5. 在 AndroidManifest.xml 对使用了自定义标题栏的Activity定义主题
1.定义一个自定义的标题栏布局 mytitlebar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/re_title" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp" //定义自定义标题栏的高度
android:background="@color/start_background"
android:orientation="horizontal">
<ImageButton
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:id="@+id/bt_back"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/left_back"
android:background="@color/touming"/>
<TextView
android:id="@+id/mytitle"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"//使文字在整个标题栏的中间
android:textColor="#fff"
android:textSize="20dp" />
</RelativeLayout >