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

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"/>


版权声明:本文为da_xin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。