2015-02-23 65 views
1

如何强制编辑文本中的特定格式。 实施例:Android:Edittext强制格式

的Userinput是:123456789AB 格式应该是:123.4567.89AB 最好是,该格式的转换是在即时。第二种解决方案是,在后台中字符串的转换,而不在Edittext中显示。

PS:在EDITTEXT在AlertBuilder

动态创建
+0

你可能会想与之合作的' DecimalFormat“类,因为您需要编程它,然后在您按照需要格式化后在”EditText“中显示文本。 – 2015-02-23 11:21:23

回答

0

添加监听器(textWatcher)到您的EditText

yourEditText.addTextChangedListener(new TextWatcher() { 

      public void afterTextChanged(Editable s) { 

      // you can call or do what you want with your EditText here 
      yourEditText. ... 

      } 

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

      public void onTextChanged(CharSequence s, int start, int before, int count) {} 
     }); 

你可以阻止它进入它。你也可以添加过滤器。

如果要过滤EditText中的输入字符,则需要使用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 (!Character.isLetterOrDigit(source.charAt(i))) { 
        return ""; 
       } 
      } 
    return null; 
    } 
     }; 

EditText text = (EditText)findViewById(R.id.edittext1); 
text.setFilters(new InputFilter[]{filter}); 
0

希望这会为你工作

yourEditText.addTextChangedListener(new TextWatcher() { 

       public void afterTextChanged(Editable s) { 
       } 

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

        if(count%3==0) 
         ((EditText)findViewById(R.id.yourEditText).setText(((EditText)findViewById(R.id.yourEditText).getText().toString()+".")); 
       } 

       public void onTextChanged(CharSequence s, int start, int before, int count) {} 
      }); 

与之相似,你可以去按您的要求