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

发布于 2024-11-19 09:19:53 字数 1846 浏览 4 评论 0原文

我想始终以两位小数显示 EditText 字段的输入。因此,当用户输入 5 时,它将显示 5.00,或者当用户输入 7.5 时,它将显示 7.50。

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

我已经将输入类型设置为:

android:inputType="number|numberDecimal"/>

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

抱歉,我对 android / java 还是很陌生......

感谢您的帮助!

编辑 2011-07-09 23.35 - 解决了第 1 部分(共 2 部分):将“”改为 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 - 解决了第 2 部分(共 2 部分):将用户输入更改为具有两位小数的数字。

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");
                }
            }
        }
    }

I would like to display the input of the EditText fields with two decimals at all times. So when the user enters 5 it will show 5.00 or when the user enters 7.5 it will show 7.50.

Besides that I would like to also show zero when the field is empty instead of nothing.

What I've got already is the inputtype set to:

android:inputType="number|numberDecimal"/>

Should I work with inputfilters here?

Sorry I still quite new to android / java...

Thanks for your help!

Edit 2011-07-09 23.35 - Solved part 1 of 2: The "" to 0.00.

With the answer of nickfox I was able to solve half of my question.

    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);
            } 
        }
    });

I'm still working on a solution for the other half of my question. If I found the solution I will post it here too.

Edit 2011-07-09 23.35 - Solved part 2 of 2: Change user input to a number with two decimals.

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");
                }
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里泪两行 2024-11-26 09:19:53

这是我用来输入美元的东西。它确保始终只有小数点后 2 位。您应该能够通过删除 $ 符号来适应您的需要。

    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());

            }

        }
    });

Here is something I use to for dollar input. It makes sure that there are only 2 places past the decimal point at all times. You should be able to adapt it to your needs by removing the $ sign.

    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());

            }

        }
    });
无力看清 2024-11-26 09:19:53

更新 #2

如果我错了,请纠正我,但官方文档为 TextWatcher 表示它合法使用 afterTextChanged 方法更改...此任务的 EditText 内容。

我在多语言应用程序中执行相同的任务,并且据我所知,可能有 . 符号作为分隔符,因此我修改 nickfox 0.00 格式的答案,符号总数限制为 10:

布局(已更新):

<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) {
            }

        });
    }

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

Update #2

Correct me if I'm wrong, but oficial docs to TextWatcher say that it's legitimate use afterTextChanged method for make changes to... EditText content for this task.

I have the same task in my multy-language app and as I know it's possible , or . symbols as separator so I modify nickfox answer for 0.00 format with total limit of symbols to 10:

Layout (Updated):

<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 class:

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);
}


}

Code in ocCreate method (Update #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) {
            }

        });
    }

It's look like the best result for me. Now this code support copy-paste actions

万劫不复 2024-11-26 09:19:53

只是对帕特里克发布的解决方案进行了一些细微的更改。我已经在 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);
    }
}
});

Just some minor changes to the solutions that patrick posted. I've implemented everything in the onFocusChangedListener. Also be sure to set the EditText input type to "number|numberDecimal".

Changes are:
If input is empty then replace with "0.00".
If input has more than two decimals of precision, then cast down to two decimals.
Some minor refactoring.

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);
    }
}
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文