引入佈局可以使佈局統一,但如果佈局中有控件要能夠响应事件,我们还是需要在每个活动中对控件进行事件的注册。
我们可以使用自定义控件的方式解决
新建TitleLayout 类并继承LinearLayout,
package com.example.layouttest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class TitleLayout extends LinearLayout implements OnClickListener{
private Button back,edit;
//复写具有两个参数的构造方法,在布局中引入TileLayout控件就会调用该构造方法
//需要在构造函数中对标题栏布局进行动态加载
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//通过LayoutInFlater.from(Context context) 构造一个LayoutInFlater对象
//通过inflate()方法动态加载一个布局文件
//inflate()有两个参数,第一个参数为需要加载的布局文件id,第二个参数是给加载好的布局加一个父佈局。
LayoutInflater.from(context).inflate(R.layout.title, this);
back = (Button)findViewById(R.id.back);
edit = (Button)findViewById(R.id.edit);
back.setOnClickListener(this);
edit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.back:
Toast.makeText(getContext(), "you clicked back button", Toast.LENGTH_SHORT).show();
break;
case R.id.edit:
Toast.makeText(getContext(), "you clicked edit button", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
复写具有两个参数的构造方法,在布局中引入TileLayout控件就会调用该构造方法,需要在构造函数中对标题栏布局进行动态加载
通过LayoutInFlater.from(Context context) 构造一个LayoutInFlater对象
通过inflate()方法动态加载一个布局文件,inflate()有两个参数,第一个参数为需要加载的布局文件id,第二个参数是给加载好的布局加一个父佈局。
然后在布局文件中添加这个自定义控件。
在layout.xml中添加自定义的控件:
<com.example.layouttest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
注意:添加自定义的控件必须指明完整的类名。