2017-04-10 56 views

回答

2

您應該根據您的要求使用InputFilter。試試下面的代碼:

InputFilter filter = new InputFilter() { 
       public CharSequence filter(CharSequence source, int start, int end, 
         Spanned dest, int dstart, int dend) { 
        for (int i = start; i < end; i++) { 
         if (source.charAt(i) == '+' && i!=start) { 
          Toast.makeText(getApplicationContext(),"Invalid Input",Toast.LENGTH_SHORT).show(); 
          return ""; 
         } 
        } 
        return null; 
       } 

      }; 

editText.setFilters(new InputFilter[] { filter }); 

希望這會有所幫助。

+2

你的答案是偉大的,但需要返回 source.toString()子(0,source.length() - 1) 而不是 「」 – Zia

+1

這只是你的'EditText'過濾器。如果用戶將其他地方放在其他地方而不是開始,這將返回「」。如果用戶正確地放置了'+',你可以稍後編輯'edittext.getText()。toString()。substring(0,source.length() - 1)'。 – tahsinRupam

0

您大概可以利用TextWatcher。如下面的代碼的東西應該服務宗旨:

txtNumbers.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) { 
     // Do the magic here 

     int positionOfPlus = txtNumbers.getText().toString().indexOf("+"); 

     if (positionOfPlus != -1 && positionOfPlus != 0) { 
      txtNumbers.setText("+" + txtNumbers.getText().toString().replace("+", "")); 
     } 
    } 
}); 

欲瞭解更多有關TextWatcher,讀到這裏:TextWatcher | Android Developers

0

這裏是代碼片段這樣的伎倆:

editText.addTextChangedListener(新TextWatcher(){

 @Override 
     public void afterTextChanged(Editable s) {} 

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

     @Override 
     public void onTextChanged(CharSequence s, int start, 
            int before, int count) { 
      // here you can check for '+' sign, and then you can remove additional '=' sign from it. 
     } 
    }); 

希望這會幫助你。