Android EditText 小數(shù)輸入優(yōu)化

———通過EditText輸入小數(shù)時(shí)盆驹,可指定整數(shù)或小數(shù)的位數(shù)

如需下載源碼,請?jiān)L問
https://github.com/fengchuanfang/DecimalInput

文章原創(chuàng)滩愁,轉(zhuǎn)載請注明出處:
Android EditText 小數(shù)輸入優(yōu)化

運(yùn)行效果如下:


小數(shù)輸入框演示.gif

在xml布局文件中躯喇,設(shè)置EditText的inputType屬性為“numberDecimal”,可限制EditText只能輸入帶小數(shù)點(diǎn)的浮點(diǎn)數(shù)硝枉,如下:

android:inputType="numberDecimal"

但是廉丽,在實(shí)際開發(fā)應(yīng)用中,發(fā)現(xiàn)只設(shè)置這個(gè)屬性來限制EditText只可輸入小數(shù)所帶來的用戶體驗(yàn)并不是很好妻味,無法滿足實(shí)際應(yīng)用場景的需求正压。

例如以下非正常格式的浮點(diǎn)數(shù)也可輸入


非正常格式浮點(diǎn)數(shù).png

在主流的app中,例如支付寶和微信對以上問題的處理也不是很好责球,
例如支付寶充值金額界面焦履,如下;


支付寶金額非正常輸入.png

首位是“.”時(shí),不具有自動補(bǔ)“0”的邏輯
微信發(fā)紅包界面雏逾,輸入金額時(shí)嘉裤,首位是“.”會自動補(bǔ)“0”,但是不具有自動刪除首位無效“0”的邏輯校套,如下:


微信紅包金額輸入首位存在無效0.jpg

而且在實(shí)際應(yīng)用時(shí)价脾,大部分情況需要限制整數(shù)或小數(shù)的位數(shù),而只通過xml設(shè)置EditText的屬性并不能很好的實(shí)現(xiàn)笛匙。

下面我們通過EditText的addTextChangedListener(TextWatcher watcher)方法侨把,添加一個(gè)文本監(jiān)視器,并結(jié)合正則表達(dá)式實(shí)現(xiàn)以上需求妹孙,同事對原始的EditText的外觀進(jìn)行美化秋柄。

寫一個(gè)小數(shù)輸入監(jiān)視類DecimalInputTextWatcher繼承自TextWatcher,代碼如下:

/**
 * 功能描述:小數(shù)輸入文本觀察類
 *
 * @author (作者) edward(馮豐楓)
 * @link http://www.reibang.com/u/f7176d6d53d2
 * 創(chuàng)建時(shí)間: 2018/3/12
 */

public class DecimalInputTextWatcher implements TextWatcher {
    private Pattern mPattern;

    /**
     * 不限制整數(shù)位數(shù)和小數(shù)位數(shù)
     */
    public DecimalInputTextWatcher() {
    }

    /**
     * 限制整數(shù)位數(shù)或著限制小數(shù)位數(shù)
     *
     * @param type   限制類型
     * @param number 限制位數(shù)
     */
    public DecimalInputTextWatcher(Type type, int number) {
        if (type == Type.decimal) {
            mPattern = Pattern.compile("^[0-9]+(\\.[0-9]{0," + number + "})?$");
        } else if (type == Type.integer) {
            mPattern = Pattern.compile("^[0-9]{0," + number + "}+(\\.[0-9]{0,})?$");
        }
    }

    /**
     * 既限制整數(shù)位數(shù)又限制小數(shù)位數(shù)
     *
     * @param integers 整數(shù)位數(shù)
     * @param decimals 小數(shù)位數(shù)
     */

    public DecimalInputTextWatcher(int integers, int decimals) {
        mPattern = Pattern.compile("^[0-9]{0," + integers + "}+(\\.[0-9]{0," + decimals + "})?$");
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String text = editable.toString();
        if (TextUtils.isEmpty(text)) return;
        if ((editable.length() > 1) && (editable.charAt(0) == '0') && editable.charAt(1) != '.') {   //刪除整數(shù)首位的“0”
            editable.delete(0, 1);
            return;
        }
        if (text.equals(".")) {                                    //首位是“.”自動補(bǔ)“0”
            editable.insert(0, "0");
            return;
        }
        if (mPattern != null && !mPattern.matcher(text).matches() && editable.length() > 0) {
            editable.delete(editable.length() - 1, editable.length());
            return;
        }
        //TODO:可在此處額外添加代碼
    }

    public enum Type {
        integer, decimal
    }
}

在方法afterTextChanged(Editable s)中對于不規(guī)范的浮點(diǎn)數(shù)輸入進(jìn)行處理蠢正,刪除首位無效的“0”骇笔,以及首位是“.”時(shí),自動補(bǔ)“0”嚣崭。

提供三個(gè)用于初始化的構(gòu)造方法笨触,

1、不限制整數(shù)位數(shù)和小數(shù)位數(shù)

    /**
     * 不限制整數(shù)位數(shù)和小數(shù)位數(shù)
     */
    public DecimalInputTextWatcher() {
    }

2雹舀、限制整數(shù)位數(shù)或著限制小數(shù)位數(shù)

    /**
     * 限制整數(shù)位數(shù)或著限制小數(shù)位數(shù)
     *
     * @param type   限制類型
     * @param number 限制位數(shù)
     */
    public DecimalInputTextWatcher(Type type, int number) {
        if (type == Type.decimal) {
            mPattern = Pattern.compile("^[0-9]+(\\.[0-9]{0," + number + "})?$");
        } else if (type == Type.integer) {
            mPattern = Pattern.compile("^[0-9]{0," + number + "}+(\\.[0-9]{0,})?$");
        }
    }

3芦劣、既限制整數(shù)位數(shù)又限制小數(shù)位數(shù)

     /**
     * 既限制整數(shù)位數(shù)又限制小數(shù)位數(shù)
     *
     * @param integers 整數(shù)位數(shù)
     * @param decimals 小數(shù)位數(shù)
     */

    public DecimalInputTextWatcher(int integers, int decimals) {
        mPattern = Pattern.compile("^[0-9]{0," + integers + "}+(\\.[0-9]{0," + decimals + "})?$");
    }

在Activity中的使用示例如下:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText decimalInputEt1 = findViewById(R.id.decimal_input_et1);
        //不限制整數(shù)位數(shù)和小數(shù)位數(shù)
        decimalInputEt1.addTextChangedListener(new DecimalInputTextWatcher());

        EditText decimalInputEt2 = findViewById(R.id.decimal_input_et2);
        //不限制整數(shù)位數(shù),限制小數(shù)位數(shù)為2位
        decimalInputEt2.addTextChangedListener(new DecimalInputTextWatcher(DecimalInputTextWatcher.Type.decimal, 2));

        EditText decimalInputEt3 = findViewById(R.id.decimal_input_et3);
        //限制整數(shù)位數(shù)為4位说榆,不限制小數(shù)位數(shù)
        decimalInputEt3.addTextChangedListener(new DecimalInputTextWatcher(DecimalInputTextWatcher.Type.integer, 4));

        EditText decimalInputEt4 = findViewById(R.id.decimal_input_et4);
        //限制整數(shù)位數(shù)為4位虚吟,小數(shù)位數(shù)為2位
        decimalInputEt4.addTextChangedListener(new DecimalInputTextWatcher( 4, 2));
    }
}

同時(shí)在xml布局文件中寸认,通過設(shè)置EditText的background屬性對EditText焦點(diǎn)輸入,失去焦點(diǎn)串慰,功能禁用時(shí)的外觀進(jìn)行美化

  <EditText
            android:id="@+id/decimal_input_et00"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:padding="10dp"
            android:gravity="start"
            android:textSize="14sp"
            android:inputType="numberDecimal"
            android:background="@drawable/input_edit_selector"/>

input_edit_selector.xml的代碼為:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/input_disabled_shape"/>
    <item android:state_focused="true" android:drawable="@drawable/input_focused_shape"/>
    <item android:drawable="@drawable/input_normal_shape"/>
</selector>

input_disabled_shape.xml的代碼為:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="4dp"/>
    <stroke android:color="@color/input_disabled_edit" android:width="1dp"/>
    <solid android:color="@color/input_disabled_edit"/>
</shape>

input_focused_shape.xml的代碼為:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="4dp"/>
    <stroke android:color="@color/input_stroke_blue" android:width="1dp"/>
    <solid android:color="@color/input_solid_white"/>
</shape>

input_normal_shape.xml的代碼為:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="4dp"/>
    <stroke android:color="@color/input_stroke_grey" android:width="1dp"/>
    <solid android:color="@color/input_solid_white"/>
</shape>

colors.xml中的各顏色值為:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="input_disabled_edit">#dbdbdb</color>
    <color name="input_stroke_blue">#7393D5</color>
    <color name="input_stroke_grey">#979797</color>
    <color name="input_solid_white">#FFFFFF</color>
</resources>

運(yùn)行之后的界面為:


EditText小數(shù)輸入優(yōu)化.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末穿挨,一起剝皮案震驚了整個(gè)濱河市菜职,隨后出現(xiàn)的幾起案子呈野,更是在濱河造成了極大的恐慌杈抢,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庆捺,死亡現(xiàn)場離奇詭異怜姿,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)疼燥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進(jìn)店門沧卢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人醉者,你說我怎么就攤上這事但狭。” “怎么了撬即?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵立磁,是天一觀的道長。 經(jīng)常有香客問我剥槐,道長唱歧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任粒竖,我火速辦了婚禮颅崩,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蕊苗。我一直安慰自己沿后,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布朽砰。 她就那樣靜靜地躺著尖滚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瞧柔。 梳的紋絲不亂的頭發(fā)上漆弄,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天,我揣著相機(jī)與錄音造锅,去河邊找鬼撼唾。 笑死,一個(gè)胖子當(dāng)著我的面吹牛备绽,可吹牛的內(nèi)容都是我干的券坞。 我是一名探鬼主播,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼肺素,長吁一口氣:“原來是場噩夢啊……” “哼恨锚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起倍靡,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤猴伶,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后塌西,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體他挎,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年捡需,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了办桨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,021評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡站辉,死狀恐怖呢撞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情饰剥,我是刑警寧澤殊霞,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站汰蓉,受9級特大地震影響绷蹲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜顾孽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一祝钢、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧若厚,春花似錦太颤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至乞封,卻和暖如春做裙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背肃晚。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工锚贱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人关串。 一個(gè)月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓拧廊,卻偏偏與公主長得像监徘,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子吧碾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容