引入布局<include layout="@layout/布局文件"/>
的技巧可以解决重复编写代码的问题,但是当有些控件需实现响应事件时,还需每个Activity中为这些控件单独实现事件注册代码。其实引入的布局中的按钮的功能是相同的,每个活动都要实现注册代码会增加重复代码。
所以,这种情况(即引入布局文件中有些控件需实现事件响应)应使用自定义控件方式解决:
如自定义标题栏:
- 布局文件title.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="@drawable/back_bg"
android:text="Back"
android:textColor="#000" />
<TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="@color/colorAccent"
android:textSize="24sp" />
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:layout_margin="5dp"
android:background="@drawable/edit_bg"
android:text="Edit"
android:textColor="#000" />
</LinearLayout>
- 新建类继承某布局,并重写构造函数,动态加载布局文件(LayoutInflater.from(context).inflate(R.layout.title, this))及添加控件所需事件注册代码
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);//动态加载布局文件
//按钮事件注册
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked Edit button",
Toast.LENGTH_SHORT).show();
}
});
}
}
- 在相关布局文件添加自定义的控件(和添加普通控件一样,只是需要完整的类名)
如我这里activity_main.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" >
<com.example.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
这样,每当在某个布局中引入自定义控件,相应的事件就已经自动实现好了,省去很多重复代码,这就是比引入布局文件方法(<include layout="@layout/布局文件"/>
)更便捷(当有些控件需实现响应事件时)