android 自定义标题栏

想自定义一个标题栏,有一种简单的做法,引入布局文件就可以啦。

我们来模仿一个简单的标题栏,即左右各一个按钮,中间一个文本。也就是说我们只要两个button和一个TextView即可

1.新建一个布局title.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"
    android:background="@drawable/title_bg">//整个布局的背景图

    <Button
        android:id="@+id/title_back"
        android:layout_width="77dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/qod"
        android:text="返回"
        android:textColor="@android:color/darker_gray" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="214dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="7dp"
        android:gravity="center"
        android:text="文本中心"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp" />

    <Button
        android:id="@+id/title_set"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/gwf"
        android:textColor="@android:color/darker_gray" />
</LinearLayout>

这个文件我们采用LinearLayout,两个按钮一个文本,使用三张图片来为布局和空间指定一个背景,你也可以直接填充颜色,title_bg.png,qod.png,gwf.png分别用于标题栏,返回按钮和设置按钮的背景。

上述文件得到的布局样式图如下:

2.别忘了在MainAcitivity中将系统自带的标题栏隐藏掉,代码如下:

 getSupportActionBar().hide();

3.可在MainAcitivity中注册按钮的监听器,用于实现某种效果,代码如下:

Button back = (Button) findViewById(R.id.title_back);
back.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
                Toast.makeText(MainActivity.this , "返回键被点击" , Toast.LENGTH_SHORT).show();
            }
        });

4.运行程序,点击返回按钮,效果图如下(其他的不用管,只需关注标题栏效果即可)

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值