关于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="用户名"