2014-12-22 71 views
1

我想要做的是限制可插入EditText中的值的範圍,如NumberPicker。爲什麼我不使用NumberPicker?因爲它需要API 11,我希望我的應用程序與API 10及以上版本兼容。 我已經設置範圍從1到120.如果用戶輸入一個數字超出該範圍,編輯文本中的文本將更改爲15.更好的方式來改變addTextChangedListener上的EditText的文本

我有這個代碼,但我認爲這不是最好的方式執行這個。

final EditText ed = ((EditText) findViewById(R.id.editMinutes)); 
TextWatcher tw = new TextWatcher() { 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     } 

    @Override 
    public void afterTextChanged(Editable s) { 
     } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     try { 
      int minutes = Integer.valueOf(s.toString()); 
      if (minutes < 1 || minutes > 120) { 
       ed.setText("15"); 
      } 
     } catch (NumberFormatException ex) { 
      ed.setText("15"); 
     } 
    } 
}; 
ed.addTextChangedListener(tw); 

我該如何改進?有沒有更好或更優雅的方式來做到這一點?

+2

IF你真的想要一個數字選擇器 - 進入AOSP源代碼,找到數字選擇器,並將其添加到你的應用程序然後使用它。數字選擇器不需要硬件支持,它只是一個GUI組件。 https://gitorious.org/atrix-aosp/frameworks_base/source/d762f063be970033314d3f77194bfe5cb284b605:core/java/android/widget/NumberPicker.java –

+0

我第二,我正在看代碼是簡單的下降。 – user210504

+0

我不'我想我可以使用外部代碼。至少不是那個尺寸。 –

回答

0

可以使用輸入濾波器來定義一個正則表達式從here採取文本觀察家

InputFilter filter= new InputFilter() { 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 

       String checkMe = dest.toString()+ source.toString(); 
       Pattern pattern = Pattern.compile("([1-9][0-9]?|1[01][0-9]|120)"); 
       Matcher matcher = pattern.matcher(checkMe); 
       boolean valid = matcher.matches(); 
       if(!valid){ 
        Log.i("", "invalid"); 
        return ""; 
       }else{ 
        Log.i("", "valid less than 120"); 
       } 
      return null; 

     } 
    }; 

    EditText editText=(EditText)findViewById(R.id.editMinutes); 
    editText.setFilters(new InputFilter[]{filter}); 

更優雅的代碼

public abstract class TextValidator implements TextWatcher { 
private final TextView textView; 

public TextValidator(TextView textView) { 
    this.textView = textView; 
} 

public abstract void validate(TextView textView, String text); 

@Override 
final public void afterTextChanged(Editable s) { 
    String text = textView.getText().toString(); 
    validate(textView, text); 
} 

@Override 
final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ } 

@Override 
final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ } 
} 

這樣使用它:

editText.addTextChangedListener(new TextValidator(editText) { 
    @Override public void validate(TextView textView, String text) { 
    /* Validation code here */ 
    } 
}); 
相關問題