背景:使用include语句可以轻松的添加一个布局到想要的布局中,增加代码的复用,可是引入的布局中的控件,想要对他进行监听并操作,又要重复写大量的代码,使用自定义控件就可以解决这样的问题。
代码实现:
1.新建布局文件layout_item.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="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回" />
<Button
android:id="@+id/more_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="More"
android:textAllCaps="false"/>
</LinearLayout>
2.新建类ItemLayout,实现布局的绑定,控件的监听:
//新建类继承LinearLayout,这里是因为引入的布局是LinearLayout所以继承他
public class ItemLayout extends LinearLayout {
private Button backBtn;
private Button moreBtn;
//添加构造方法
public ItemLayout(final Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//绑定布局
LayoutInflater.from(context).inflate(R.layout.layout_item,this);
backBtn = findViewById(R.id.back_btn);
moreBtn = findViewById(R.id.more_btn);
//设置监听
backBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "点击返回按钮", Toast.LENGTH_SHORT).show();
}
});
moreBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "点击More按钮", Toast.LENGTH_SHORT).show();
}
});
}
}
3.在MainActivity布局文件中引用自定义类:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.uicustomviews.MainActivity">
<com.example.uicustomviews.entity.ItemLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.uicustomviews.entity.ItemLayout>
</LinearLayout>