Android金额输入EditText共通方法

代码改变世界

EditText输入框实现最多到小数点后两位(金额显示)

package com.lianpos.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by wangshuai on 2017/11/29 0029.
 */

public class MoneyEditText {
    public static void setPricePoint(final EditText editText) {

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });
    }
}

  使用方法:

MoneyEditText.setPricePoint(number_unit_edit);

  number_unit_edit是edittext,如下:

<EditText
            android:id="@+id/number_unit_edit"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@null"
            android:gravity="right"
            android:hint="0.00"
            android:maxLength="7"
            android:inputType="numberDecimal"
            android:padding="15dp"
            android:textColor="#333333"
            android:textSize="16dp" />

  

posted @ 2018-01-03 10:48  改变世界的老十七  阅读(992)  评论(0编辑  收藏  举报