引入布局 标题栏的2种引用方式

本文介绍了在Android应用中引入标题栏的两种方法。第一种是通过`include`标签,创建layout_title.xml布局文件并在layout_main.xml中引入,同时在MainActivity中隐藏原生标题栏。第二种方法是自定义TitleLayout控件,继承LinearLayout,通过LayoutInflater动态加载布局文件。

1. 使用include 引入

1.1  创建一个layout_title.xml布局,用于布放状态栏的控件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal">

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

1.2 在layout_main.xml中引入这个布局

 <include layout="@layout/layout_title"/>

1.3 需要在MainActivity 中将自带的标题栏隐藏

      ActionBar actionBar = getSupportActionBar();
        if(actionBar != null)
        {
            actionBar.hide();
        }

2. 自定义控件方式

2.1  创建 TitleLayout 继承与 LinearLayout,LinearLayout有两个参数的构造函数,
在布局中引用这个自定义的TitleLayout控件 就会执行这个构造函数
首先使用LayoutInflater.from得到对象,再使用inflate方法动态加载布局
R.layout.layout_title:需要加载的布局文件

this:加载好的布局的父布局

public class TitleLayout extends LinearLayout
{

    public TitleLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_title,this);
    }
}

2.2 在layout_main.xml 中使用自定义布局

   <com.example.a123.menutest.TitleLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值