Android之必填项的便捷判定--TypedArray(下)

本文探讨了在Android中处理多个Edittext必填项的方法,建议使用单例模式创建注册器来动态注册Edittext,并在保存前进行判断。这种方法避免了反射操作,减少了耗时。通过XML、View和自定义Edittext注册,以及在基类Activity的onDestroy中解绑,实现了方便的必填项检查。同时,文章提到了在XML注册方式下EditText的getText值可能为空的问题,期待解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于Android的必填项,包括登陆、注册等,因为Edittext比较少,所以大多数人选择gettext然后一一判空,但是如果Edittext比较多的时候,就比较繁琐了。考虑到优化方案有二:1、重写Edittext,然后利用注册,在保存时判定每个Edittext;二、考虑到所有的数据最后都会保存成一个类,所以不管Edittext,保存之前只判断自定义类。本文主要阐述第一种方式,优点是不需要反射,耗时短。

首先,我们看效果图:

实现方法:用单例模式建立注册器,支持动态注册,注册方式有xml,view以及自定义的Edittext,考虑到多Activity的操作与复用,Edittext集合采用CopyOnWriterArrayList,全局集合采用ConcurrentHashMap。最后解绑的时候只需要在基类Activity的onDestroy方法中进行UNRegister即可,非常的方便。

最后,前端Activity的代码:

public class CustomEditActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_edittext);
    }

    public void onCheck(View view){
        EditTextUtil.getInstance().checkEmpty(this);
    }

    @Override
    protected void onDestroy() {
        EditTextUtil.getInstance().unRegister(this);
        super.onDestroy();
    }
}

与其对应的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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">
    <java.wen.com.view.EmptyEditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="用户名"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值