创建自定义控件
创建Android项目
创建自定义控件布局文件
在res/layout目录下新建title.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:background="@color/cardview_dark_background"
>
<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:text="Back"
/>
<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="@color/white"
android:textSize="24sp"
/>
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="Edit"
/>
</LinearLayout>
引入自定义控件
在activity_main.xml中引入
<?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"
tools:context=".MainActivity">
<include layout="@layout/title"/>
</LinearLayout>
启动app即可看到效果
给自定义控件按钮添加通用方法
- 重写了
LinearLayout中带有两参数的构造函数,在布局文件中引入自定义控件(title.xml)时,会调用这个构造函数。 - 使用
LayoutInflater实现动态加载,其from()方法可构建一个LayoutInflater对象,然后调用inflate()方法动态加载一个布局文件inflate()方法的第一个参数是:要加载的布局文件id- 第二个参数是:给要加载的布局文件添加父布局
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
}
}
在activity_main.xml中重新引入
<?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"
tools:context=".MainActivity">
<com.example.uniapplication.common.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
编写监听事件
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button titleBack = findViewById(R.id.title_back);
Button titleEdit = findViewById(R.id.title_edit);
titleBack.setOnClickListener(v -> ((Activity) getContext()).finish());
titleEdit.setOnClickListener(v -> Toast.makeText(getContext(), "You click Edit button",
Toast.LENGTH_SHORT).show());
}
}

浙公网安备 33010602011771号