2014-05-08 57 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试过这个,但我认为这将工作。 希望这会有所帮助。 :)