2017-03-18 126 views
-1

我必須格式化編號,因爲用戶在Edit Text中輸入編號。如果用戶輸入單個數字,則應該出現0,0x。如果用戶輸入兩位數字,則應該出現0,xx。如果三位數然後x,xx。如果四位數然後xx,xx。如果五位數然後xxx,xx。如果六位數然後x.xxx,xx。如果七位數然後xx.xxx,xx。如果八位數然後xxx.xxx,xx。任何人都可以幫我嗎?提前致謝。當用戶在編輯文本中輸入數字時的格式編號

+0

做你想做的所有零接受特定的字符串後? – Mohit

+0

爲什麼在輸入三位數時沒有'0'? – Mohit

+0

在x,xx中可以有0個。 –

回答

0

你可以使用addTextChangedListener

editText.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) { 
      // Write your logic here to parse the text 
      // and format it in the way you want to. 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    }); 
0

您可以嘗試如下:

new TextWatcher() { 

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

      if(afterFormat){ 
       afterFormat = false; 
       return; 
      } 
      afterFormat = true; 
      // TODO format digits 
      ...... 
} 
+0

我已經嘗試過,但這種方法進入循環和鍵盤掛起 –

0

你可以通過輸入濾波器設置爲文本字段實現這一目標。

private InputFilter myFilter = new InputFilter(){ 

    @Override 
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
     //your code to modify the input text. 
     return modified_input; 
    } 
}; 
editText.setFilters(new inputFilterp[]{}) 
0

這是一個方法,通過它可以實現通過addTextChangedListener或類似的東西,即

  1. 監視器文字變化..
  2. 當你得到的字符串,對於迭代它0直到它達到八位數 。

    while (string.length() < 8) { 
        string = "0" + string; 
    } 
    
  3. 所需格式的模式字符串與String.format()

    String.format("%s.%s,%s", string); // pattern you want 
    

因此,這裏是全碼:

edit.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
      text.setText(""); 
     } 
     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
     } 
     @Override 
     public void afterTextChanged(Editable s) { 
      String string = s.toString(); 
      if (string.length() < 8) { 
       while (string.length() < 8) { 
        string = "0" + string; 
       } 
      }    
      text.setText(String.format("%s.%s,%s", string.substring(0, 3), string 
        .substring(3, 6), string.substring(6, 8))); 
     } 
}); 
相關問題