自定义控件实例讲解

本文介绍如何通过自定义控件简化Android应用布局,避免重复代码。通过创建包含按钮等元素的自定义ItemLayout,轻松实现在不同场景下的复用,并为按钮添加点击监听。
背景:使用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>
over
效果展现:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

intoSunshine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值