自定义Android标题栏修改TitleBar的布局

自定义Android标题栏修改TitleBar的布局

Android程序默认的Activity标题栏只能显示一段文字,而且不能改变它的布局、颜色、标题栏的高度等。如果想要在标题栏加上个图标、button、输入框、进度条、修改标题栏颜色等,只能使用自定义的标题栏。自定义标题栏可以通过在onCreate函数中添加以下代码来实现,需要注意的是代码的顺序必须按照下面的样式,否则将无效。

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);(注意顺序)

setContentView(R.layout.mainactivity);    //Activity的布局
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar);   //标题栏的布局


如布局文件为下面:

R.layout.titlebar

 

<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
         xmlns:android = "http://schemas.android.com/apk/res/android"
         android:orientation = "horizontal"
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
>
         < TextView
                 android:text = "@string/app_name"
                 android:textColor = "#000"
                 android:paddingRight = "3.0dip"
                 android:layout_width = "wrap_content"
                 android:layout_height = "wrap_content" />
         < TextView
                 android:text = "@string/battery_text"
                 android:textColor = "#000"
                 android:paddingRight = "3.0dip"
                 android:layout_width = "wrap_content"
                 android:layout_height = "wrap_content" />
         < TextView
                 android:id = "@+id/battery_text"
                 android:textColor = "#00f"
                 android:layout_width = "wrap_content"
                 android:layout_height = "wrap_content" />
</ LinearLayout >

虽然上面这样可以在标题栏加入一些控件,但是仍然不能改变标题栏的高度、背景色,要想达到这个目的,只能使用theme(主题)。因此往project里先添加一个style。改变背景色修改android:windowTitleBackgroundStyle的值,改变标题栏高度则修改android:windowTitleSize的值。下面是一个示例:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CustomWindowTitleBackground">
        <item name="android:background">#778899</item>//标题栏的背景色
    </style>
    <style name="activityTitlebar" parent="android:Theme">
        <item name="android:windowTitleSize">32dp</item>//标题栏的高度
        <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
    </style>
</resources>

接着再修改AndroidManifest.xml文件,找到要自定义标题栏的Activity,添加上android:theme值,比如:

<activity android:name=".MainActivity" android:theme="@style/activityTitlebar">

android:theme值就是上面那个style.xml文件里定义的一个style的name值。(即上面的activityTitlebar)

按照以上的步骤,修改标题栏布局、高度、背景色的功能就实现了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值