一、在android app开发中,常常用到写自己的控件来满足自己的开发需求。我这里需求是限制某个EditText 输入的首个字母不能是0。
二、增加标签属性来配置控件属性步骤。
2.1、在res/values/目录下添加在资源文件attrs.xml,增加 declare-styleable 节点,name为自定义控件名字;
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LimitEditText">
<attr name="imageResource1" format="reference" />
<attr name="imageResource2" format="reference" />
<attr name="zero_first" format="boolean" />
<attr name="text2" format="string" />
<attr name="showSpot" format="boolean" />
</declare-styleable>
</resources>
2.2 xml 布局文件, app:zero_first是我自己添加的属性,等于true的话才允许编辑框的首个字符是0.
<com.xxx.xxx.LimitEditText
android:id="@+id/config_voltage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:maxLines="1"
android:singleLine="true"
app:zero_first="true"
android:digits="0123456789."
android:text="1.0" />
2.3 在自定义控件文件中解析配置的参数zero_first,我这个EditText编辑框是继承过来的。
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LimitEditText);
zero_first = typedArray.getBoolean(R.styleable.LimitEditText_zero_first, false);
2.4 LimitEditText.java文件需要修改的内容
2.5 这样输入的第一个字符就不能是0了
三、参考文章