一、仅引入布局文件
1、 新建一个xml布局文件title.xml,写入自定义布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:background="#B06DFA"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/butBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/back"></ImageButton>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="POWER MANAGER"
android:layout_gravity ="center"
android:gravity="left"
android:layout_weight="2"
android:layout_margin="5dp"></TextView>
<ImageButton
android:id="@+id/butInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/info"></ImageButton>
</LinearLayout>
2、在我们要引入title的布局文件中包含title,使用include
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="@layout/title"></include>
</androidx.constraintlayout.widget.ConstraintLayout>
这一种方法仅仅把ui引入了,但是ui里控件的功能还需要引入一次写一次,第二种方法把这个功能也封装起来。
二、把控件功能也封装起来
1、还是要写布局文件,同方法一的1
2、新建java类TitleLayout 继承 LinearLayout
public class TitleLayout extends LinearLayout {
public TitleLayout(Context contex, AttributeSet attrs)
{
super(contex,attrs);
LayoutInflater.from(contex).inflate(R.layout.title,this);
ImageButton butBack=findViewById(R.id.butBack); //返回图标按钮
ImageButton butInfo=findViewById(R.id.butInfo); //详细信息按钮
butBack.setBackgroundResource(0); //隐藏背景
butInfo.setBackgroundResource(0);
//返回按钮
butBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(contex, "click:back", Toast.LENGTH_SHORT).show();
}
});
//详细信息按钮
butInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(contex, "click:info", Toast.LENGTH_SHORT).show();
}
});
}
}
3、在我们要引入title的布局文件中,像普通控件一样,不能再用include
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.test.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"></com.example.test.TitleLayout>
</androidx.constraintlayout.widget.ConstraintLayout>