Android—自定义标题栏的实现及遇见的问题解决

开发者设计界面时候往往不会使用系统自带的标题栏,因为不美观,所以需要自己设置标题栏。

1.根据需求在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="match_parent"
    android:background="#1e9ee1" >

    <TextView
        android:id="@+id/tv_titlename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="标题"
        android:textColor="#fff"
        android:textSize="18sp" />

    <Button
        android:id="@+id/brn_search_back"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignBottom="@+id/tv_titlename"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="16dp"
        android:background="@drawable/mreturn" />

    <ImageView
        android:id="@+id/iv_basetitlewring"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/tv_titlename"
        android:layout_marginRight="16dp"
        android:background="#0000" />

</RelativeLayout>

2.在values的styles中将以上标题设置成自己的style

 <style name="CustomTheme" parent="AppBaseTheme">
        <item name="android:windowTitleSize">48dip</item>
    </style>

3.在醒目清单文件中用到该主题的activity的标签中加入 android:theme="@style/CustomTheme"

4.在activity的java文件的onCreate()方法中编辑以下代码:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                R.layout.base_title);

注意:只写上面这些的话有可能在 setContentView(R.layout.activity_main);这句会报空指针异常导致程序停止运行

解决:在values的styles中自己的主题加 <item name="android:windowActionBar" tools:ignore="NewApi">false</item>(亲测可用)

希望能给大家带来帮助谢谢。

posted @ 2016-05-06 13:56  奋斗者—cyf  阅读(2062)  评论(0编辑  收藏  举报