EditText始终显示带有2位小数的数字

12

我希望在EditText字段中始终以两位小数显示输入内容。因此,当用户输入5时,它将显示为5.00,或者当用户输入7.5时,它将显示为7.50。

除此之外,我还希望在字段为空时显示零而不是什么都没有。

我已经设置了inputtype:

android:inputType="number|numberDecimal"/>

我应该在这里使用输入过滤器吗?

抱歉,我对Android/Java还很陌生...

谢谢你的帮助!

编辑 2011-07-09 23.35 - 解决了问题的一部分:将“”更改为0.00。

在nickfox的回答下,我解决了我的问题的一半。

    et.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(s.toString().matches(""))
            {
                et.setText("0.00");
                Selection.setSelection(et.getText(), 0, 4);
            } 
        }
    });

我仍在为我的问题的另一半寻找解决方案。如果我找到了解决方案,我也会在这里发布。

编辑 2011-07-09 23.35 - 解决了第二个问题: 将用户输入更改为带有两位小数的数字。

OnFocusChangeListener FocusChanged = new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus){
            String userInput = et.getText().toString();

            int dotPos = -1;    

            for (int i = 0; i < userInput.length(); i++) {
                char c = userInput.charAt(i);
                if (c == '.') {
                    dotPos = i;
                }
            }

            if (dotPos == -1){
                et.setText(userInput + ".00");
            } else {
                if ( userInput.length() - dotPos == 1 ) {
                    et.setText(userInput + "00");
                } else if ( userInput.length() - dotPos == 2 ) {
                    et.setText(userInput + "0");
                }
            }
        }
    }

你能不能用 int dotPos = userInput.indexOf('.'); 来替换你的 for 循环呢?indexOf() 方法甚至会在未找到字符时返回 -1。此外,之后你能不能使用 switch case 语句呢? - ArtOfWarfare
另外,你的解决方案如果字符串中有太多小数位是无法去除它们的。 - ArtOfWarfare
3个回答

18

以下是我用来输入美元的代码,它可以确保小数点后只有两位。你可以根据自己的需要删除美元符号并进行修改。

    amountEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    amountEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
            {
                String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                StringBuilder cashAmountBuilder = new StringBuilder(userInput);

                while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                    cashAmountBuilder.deleteCharAt(0);
                }
                while (cashAmountBuilder.length() < 3) {
                    cashAmountBuilder.insert(0, '0');
                }
                cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
                cashAmountBuilder.insert(0, '$');

                amountEditText.setText(cashAmountBuilder.toString());
                // keeps the cursor always to the right
                Selection.setSelection(amountEditText.getText(), cashAmountBuilder.toString().length());

            }

        }
    });

嗨,Nickfox,感谢你的回答。我正在尝试让它工作,但问题是当它想要设置文本时会导致FC。有什么想法是什么原因引起的吗?谢谢! - patrick
这有助于找到解决方案。有关实施的解决方案,请参见问题。再次感谢Nickfox! - patrick
3
我不需要美元符号,我试图移除现金金额构建器中的'$',但它导致应用程序崩溃。有什么帮助吗? - Ravi Bhandari
如何从这个模式中删除 $ 符号? - kunal
我试图将 $ 更改为其他货币,但之后它崩溃了。有什么帮助吗?谢谢。 - natsumiyu

4

更新 #2

请纠正我,但TextWatcher的官方文档说,afterTextChanged方法是用于修改 EditText 内容以完成此任务的合法用途。

我的多语言应用程序中也有同样的任务,我知道可以使用,.作为分隔符,因此我修改了nickfox的答案来实现10个字符的0.00格式:

布局(已更新):

<com.custom.EditTextAlwaysLast
        android:id="@+id/et"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:maxLength="10"
        android:layout_marginTop="50dp"
        android:inputType="numberDecimal"
        android:gravity="right"/>

EditTextAlwaysLast类:

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * Created by Drew on 16-01-2015.
 */
public class EditTextAlwaysLast extends EditText {

    public EditTextAlwaysLast(Context context) {
        super(context);
    }

    public EditTextAlwaysLast(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditTextAlwaysLast(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
    //if just tap - cursor to the end of row, if long press - selection menu
        if (selStart==selEnd)
            setSelection(getText().length());
       super.onSelectionChanged(selStart, selEnd);
}


}

ocCreate方法中的代码(更新#2):

EditTextAlwaysLast amountEditText;
    Pattern regex;
    Pattern regexPaste;

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


        amountEditText = (EditTextAlwaysLast)findViewById(R.id.et);


        DecimalFormatSymbols dfs = new DecimalFormatSymbols(getResources().getConfiguration().locale);
        final char separator =  dfs.getDecimalSeparator();

        //pattern for simple input
        regex = Pattern.compile("^(\\d{1,7}["+ separator+"]\\d{2}){1}$");
        //pattern for inserted text, like 005 in buffer inserted to 0,05 at position of first zero => 5,05 as a result
        regexPaste = Pattern.compile("^([0]+\\d{1,6}["+separator+"]\\d{2})$");

        if (amountEditText.getText().toString().equals(""))
            amountEditText.setText("0"+ separator + "00");

        amountEditText.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                if (!s.toString().matches(regex.toString())||s.toString().matches(regexPaste.toString())){

                    //Unformatted string without any not-decimal symbols
                    String coins = s.toString().replaceAll("[^\\d]","");
                    StringBuilder builder = new StringBuilder(coins);

                    //Example: 0006
                    while (builder.length()>3 && builder.charAt(0)=='0')
                        //Result: 006
                        builder.deleteCharAt(0);
                    //Example: 06
                    while (builder.length()<3)
                        //Result: 006
                        builder.insert(0,'0');
                    //Final result: 0,06 or 0.06
                    builder.insert(builder.length()-2,separator);
                    amountEditText.setText(builder.toString());
                }
                amountEditText.setSelection(amountEditText.getText().length());
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

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

        });
    }

看起来这对我来说是最好的结果。现在,此代码支持复制和粘贴操作。


2

对于 Patrick 发布的解决方案,进行了一些细微的更改。我已经在 onFocusChangedListener 中实现了所有功能。同时请确保将 EditText 的输入类型设置为 "number|numberDecimal"。

更改内容包括: 如果输入为空,则替换为 "0.00"。 如果输入的精度超过两位小数,则截断至两位小数。 进行了一些小的重构。

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) {
    if (!hasFocus) {
        String userInput = ET.getText().toString();

        if (TextUtils.isEmpty(userInput)) {
            userInput = "0.00";
        } else {
            float floatValue = Float.parseFloat(userInput);
            userInput = String.format("%.2f",floatValue);
        }

        editText.setText(userInput);
    }
}
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接