如何将EditText默认为整数,但允许十进制输入? [英] How to default an EditText to integer but allow decimal input?

查看:174
本文介绍了如何将EditText默认为整数,但允许十进制输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个EditText来允许用户输入一个存储在Double中的值。

I am using an EditText to allow a user to input a value that is stored in a Double.

但是,默认情况下,双倍看起来像0.0,而如果用户不使用额外的十进制空格,这有点烦人。有没有办法强制显示整个数字看起来像0,只有当用户确实使用它时才显示小数?

However, by default, Doubles look like "0.0" and it's a little annoying for a user to backspace over the extra decimal if it's not used. Is there a way to force-display whole numbers to look like "0" and only show the decimal if the user actually decides to use it?

当前代码: p>

Current code:

        myEditText = (EditText) view.findViewById(R.id.my_edittext);
        myEditText.setText(myVariable + "");
        myEditText.addTextChangedListener(new TextWatcher() {
            @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 s) {
                String temp = s.toString();
                if (s.length() > 0){
                    if (OtherMethods.isDouble(temp)) {
                        myVariable = Double.parseDouble(temp);
                    }
                    else {
                        myVariable = 0.0;
                    }
                }
                else {
                    myVariable = 0.0;
                }
            }
        });

XML:

<EditText
    android:id="@+id/my_edittext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:ems="10"
    android:hint="Input Value"
    android:imeOptions="actionDone"/>


推荐答案


  1. Double to String,然后String到Int:

  1. Parsing Double to String, then String to Int:

String stringparsed = YourDouble + "";
int intparsed = Integer.parseInt(stringparsed);


  • 使用子字符串将字符串从一个startIndex剪切到finalIndex:

  • Using substring to cut the string from a startIndex to finalIndex:

    String stringparsed = YourDouble + "";
    String final = stringparsed.substring(0,1);   //for example, if the double was    0.0, the result is 0
    


  • 这篇关于如何将EditText默认为整数,但允许十进制输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆