新建一个布局 title.xml 代码如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000">
<Button
android:id="@+id/button_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="back"
android:background="#fff"
android:textColor="#000"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title"
android:textColor="#fff"
android:textSize="24sp"/>
<Button
android:id="@+id/button_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:background="#fff"
android:text="Edit"
android:textColor="#000"/>
</LinearLayout>
在xml中添加< include layout=”@layout/title”/>
新建一个TitleLayout继承LinearLayout,代码如下
首先重写LinearLayout中的带两个参数的构造函数
布局中引入TitleLayout控件就会调用这个构造函数
然后在构造函数中对标题栏布局进行动态加载,需要借助LayoutInfater来进行实现。通过LayoutInfater的from()方法可以构造出一个LayoutInfater对象,调用inflate()方法动态加载一个布局文件
inflate方法需要两个参数 一是id 二是加载好的布局文件再添加一个父布局,这里我们指定为TitleLayout 所以传入this
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs){
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.table_layout,this);
}
}
再布局文件中添加这个自定义控件 修改xml中的代码
<com.example.kingshan.uiwidgettest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.kingshan.uiwidgettest.TitleLayout>
然后就可以注册点击响应事件