String 회전 Float 질문

3178 단어 일상적인 문제
오늘 프로젝트에서 String에서 Float로 전환하는 버그를 발견했습니다. 구체적인 원인은 EditText에 여러 개를 입력했기 때문입니다."또는 이 시작 입력 ".하면, Float를 진행하고 있습니다.parse Float(String str) 때 이상을 던지면 프로그램 crash가 떨어집니다!
현재 자신의 해결 방안은 문자열에 대한 수동 판단입니다!구체적인 코드는 다음과 같습니다.
EditText et = (EditText) rootView.findViewById(R.id.et);
            et.addTextChangedListener(new TextWatcher() {

                @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String str = s.toString();
                    if (TextUtils.isEmpty(str)) {
                        return;
                    }
                    int firstIdex = str.indexOf(".");
                    int lastIndex = str.lastIndexOf(".");
                    if (firstIdex == lastIndex && firstIdex != 0) {//                    
                    Float valueOf = Float.valueOf(str);
                        float float1 = Float.parseFloat(str);
                        Log.e("zhilong", valueOf + "--" + float1);
                    } else {
                        if (str.length() == 1) {
                            et.setText("");
                        } else {
                            et.setText(str.substring(0, str.length() - 1));
                            et.setSelection(str.length()-1);

                        }
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

좋은 웹페이지 즐겨찾기