Android自定义Title Bar

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目录下的文件


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值