簡體   English   中英

如何將EditText默認設置為整數但允許十進制輸入?

[英]How to default an EditText to integer but allow decimal input?

我正在使用EditText允許用戶輸入存儲在Double中的值。

但是,默認情況下,雙打看起來像“ 0.0”,如果用戶不使用多余的小數,則退格會有點煩人。 有沒有一種方法可以強制將整數顯示為“ 0”,並且僅在用戶實際決定使用時才顯示小數?

當前代碼:

        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解析為String,然后將String解析為Int:

     String stringparsed = YourDouble + ""; int intparsed = Integer.parseInt(stringparsed); 
  2. 使用子字符串將字符串從startIndex剪切為finalIndex:

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

為此,您可以使用NumberFormat

    EditText yourEditText = (EditText) findViewById(R.id.editTextID);
    //dummy data, will have user's value
    double aDouble = 4.0;

    //formats to show decimal
    NumberFormat formatter = new DecimalFormat("#0");

    //this will show "4"
    yourEditText.setText(formatter.format(aDouble));

確保驗證用戶的輸入。 同樣,這只會修改顯示的內容,而不會修改值本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM