Android 自定义标题栏Title Bar

在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>
这样就基本上完成了自定义title bar,但是有个问题,App首次载入时,系统总是会闪现一下app_name,然后才会运行我们定义的title bar行为。这是一个令人诡异的行为。那么怎么去除app_name呢?

首先我们可以在app的manifest文件中,给我们的Activity添加无标题栏的主题

android:theme="@android:style/Theme.NoTitleBar" 

然后重新声明自定义的TitleBar,代码如下:

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); //注意顺序

附上styles.xml

<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>
效果图如下:



你可能感兴趣的:(自定义TitleBar)