How to determine if an input in EditText is an integer?

后端 未结 7 2126
轻奢々
轻奢々 2021-02-12 12:48

Hi I\'m a newbie in Android Programming.

I\'m trying to build an activity which includes an edittext field and a button. When user type in an

7条回答
  •  忘掉有多难
    2021-02-12 13:28

    Try this solution.

    You need to add the properties android:nextFocusDown="@+id/nextedittext_id" and android:singleLine="true" in your edittexts.

    For example:

    
    
    
     
    

    And add the following code in your activity:

     editText1.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) {
                    String value=s.toString();
                        if(isNumeric(value)){
                            if(Integer.parseInt(value)>=100){
                                editText1.setFocusableInTouchMode(true);
                                editText1.setFocusable(false);
                            }
                    }
                }
    
                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            editText2.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    editText1.setFocusableInTouchMode(true);
                    editText1.setFocusable(true);
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                }
    
                @Override
                public void afterTextChanged(Editable s) {
    
                }
            });
    

    isNumeric method is as same as above:

     public static boolean isNumeric(String str)
        {
            return str.matches("-?\\d+(.\\d+)?");
        }
    

提交回复
热议问题