引入布局的技巧确实解决了重复编写布局代码的问题,但是如果布局中有一些控件要求能够响应事件,我们还是需要在每个活动中为这些控件单独编写一次事件注册的代码。比如标题栏中的返回按钮,其实不管在哪一个活动中,这个按钮的功能都是相同的,即销毁掉当前活动。而如果在每一个活动中都需要重新注册一遍返回按钮的点击事件,无疑又是增加了很多重复的代码,这种情况最好是使用自定义控件的方式来解决。
layout_title.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0000ff"
>
<ImageView
android:id="@+id/iv_title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/layout_title_selector"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="@string/single_model"
android:textSize="20sp"
android:textColor="#ffffff" />
</RelativeLayout>
自定义控件
public class TitleLayout extends RelativeLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.layout_title, this);
ImageView back = (ImageView) findViewById(R.id.iv_title_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
}
}
引用自定义布局控件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.zy.tiger.activity.TitleLayout
android:id="@+id/tl_single_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.zy.tiger.activity.TitleLayout>
</RelativeLayout>