첫문자를 숫자를 입력할 경우숫자만 입력되고

첫문자를 영어를 입력할 경우 영어만 입력되는 예제


private EditText mEdit;


@Override

protected void onCreateX(Bundle savedInstanceState) {

mEdit = (EditText)findViewById(R.id.test_edit);

mEdit.addTextChangedListener(new TextWatcher() {

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

// TODO Auto-generated method stub

if(count == 0){

mEdit.setFilters(new InputFilter[]{filterAll});

}else if(count == 1){

if(isNumber(s.toString())){

mEdit.setFilters(new InputFilter[]{filterNum});

}else{

mEdit.setFilters(new InputFilter[]{filterEng});

}

}

}

@Override

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

// TODO Auto-generated method stub

}

@Override

public void afterTextChanged(Editable s) {

// TODO Auto-generated method stub

}

});

}

   public static boolean isNumber(String str){

       boolean result = false;

       try{

           Double.parseDouble(str) ;

           result = true ;

       }catch(Exception e){}


       return result ;

   }

    

    private InputFilter filterNum = new InputFilter() {

@Override

public CharSequence filter(CharSequence source, int start, int end,

Spanned dest, int dstart, int dend) {

// TODO Auto-generated method stub

Pattern ps = Pattern.compile("^[0-9]+$");

if(!ps.matcher(source).matches()){

return "";

}

return null;

}

};

    private InputFilter filterEng = new InputFilter() {

@Override

public CharSequence filter(CharSequence source, int start, int end,

Spanned dest, int dstart, int dend) {

// TODO Auto-generated method stub

Pattern ps = Pattern.compile("^[a-zA-Z]+$");

if(!ps.matcher(source).matches()){

return "";

}

return null;

}

};

    private InputFilter filterAll = new InputFilter() {

@Override

public CharSequence filter(CharSequence source, int start, int end,

Spanned dest, int dstart, int dend) {

return source;

}

};




728x90
반응형

+ Recent posts