2014-05-08 59 views
1

在我的應用我必須格式化2個EditTexts的輸入,如:安卓:EditText上輸入格式

  • 1234 4567 67:即由四個分組的十位數。 (該空間自動,未由用戶插入)
  • 11/14:用'/'分隔的四位數字。 (自動插入'/')

我不知道該怎麼做。請幫助:

回答

1

我能想到的實現它的方法有兩種:

使用addTextChangedListener

yourEditText.addTextChangedListener(new TextWatcher() { 

      public void afterTextChanged(Editable s) { 

      // Do your tricks here 

      } 

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

      public void onTextChanged(CharSequence s, int start, int before, int count) {} 
     }); 
  • 創建自定義Edittexts
    This link不會做你在找什麼,但會給你一個想法如何創建自定義EditText。
1

使用「onKeyListener」獲取輸入事件。 EditText OnKeyDown

然後檢查輸入是否正確並計數。在代碼中添加空格/斜槓。 示例代碼:

if (editText.getText.toString().length() % 4 == 0) editText.setText(editText.getText.toString() + " "); 

沒有通過自己嘗試一下,但是這將是這樣我會嘗試。另外我也會檢查數字輸入。

2

將一個監聽器放在編輯文本上作爲afterTextChanged。 使用length()函數獲取數字位數。 獲得數字位數後,可以提取每個數字,然後在適當的位置插入'/'空格。

len=editText.getText.toString().length(); 

然後你可以通過檢查長度做適當的改變。

num=Integer.parseInt(editText.getText.toString()); 
    temp=num; 
    if(len>=10) 
    { 
    A: 
    if((len-4)>0) 
    { 
    for(i=0;i<(len-4);i++) 
    { 
    temp=temp/10; //we get the first 4 digits 
    } 
    editText.setText(temp+" "); //place letters and add space 
    temp=num%(10^(len-4));  //get the num without the first-4 letters 
    len=len-4;   //modify length 
    goto A;  //repeat again 
    } 
    editText.setText(temp);  //add the last remaining letters 
    } 
    else if(len==4) 
{ 
temp=num; 
temp=temp%100; //store the last 2 digits 
num=num/10;  //get the first 2 digits 
editText.setText(num+"/"+temp); 
} 

我havnt試過這個,但我認爲這將工作。 希望這會有所幫助。 :)