如何在editText中设置字符串格式

时间:2016-06-14 19:15:43

标签: android string android-edittext

我希望字符串显示在我的EditText中,如:

"AA-BB-11",但我只需要放在AABB11内,这可能吗?

1 个答案:

答案 0 :(得分:2)

我认为你必须实现TextWatcher。尝试类似的东西:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText test = (EditText) findViewById(R.id.editText) 
        test.addTextChangedListener(this);
    }

    @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 text) {
      if (text.length() == 2 || text.length() == 5) {
        text.append('-');
      }
    }

请参阅:https://developer.android.com/reference/android/text/TextWatcher.html

编辑:

您可以在此处查看完整代码:https://stackoverflow.com/a/28043245/6450234

您只需按text.length() == 3 || text.length() == 7

更改text.length() == 2 || text.length() == 5即可