Android自定义控件——全局返回标题栏

效果图

左边的back按钮实现在全局任意位置返回
在这里插入图片描述

全局返回标题栏

通过继承LinearLayout,为Button设置点击事件,调用Activity的finish()方法可以实现全局返回

创建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">

    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="back" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="43dp"
        android:layout_weight="1"
        android:background="#fff000"
        android:gravity="center"
        android:text="Title" />

    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Edit" />
</LinearLayout>

创建TitleLayout继承LinearLayout,加载布局和设置点击事件:

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        Button titleBack = findViewById(R.id.title_back);
        Button titleEdit = findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();
            }
        });
        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }
}

在activity_main.xml中加入TitleLayout:

<com.example.demo0.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

在Activity中取消原有标题栏:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.hide();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值