我们可以创建自己的布局组件,方便项目中复用。
创建一个自定义布局需要:
1、创建xml布局文件;
2、新建类继承自父布局类,例如LinearLayout。
创建布局文件
my_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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:text="这是标题" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="编辑"
android:textColor="#fff" />
</LinearLayout>
新建类继承自父布局类:
MyTitleLayout.java
package com.a52fhy.learnlayout;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
/**
* Created by YJC on 2017/12/16 016.
*/
public class MyTitleLayout extends LinearLayout{
public MyTitleLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.my_title, this);
}
}
我们还可以在这个类对布局文件里界面元素绑定事件。
然后引用这个自定义组件:
<com.a52fhy.learnlayout.MyTitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.a52fhy.learnlayout.MyTitleLayout>