【问题标题】:Zip code with dash带破折号的邮政编码
【发布时间】:2016-03-30 08:57:45
【问题描述】:

在 android EditText 中可以使用破折号编写邮政编码(例如“55-555”)。中间只有一个破折号。我的意思是我想在数字键盘上添加破折号(“-”)。

【问题讨论】:

  • android:digits="0123456789-"
  • 但是我可以编程吗?我的意思是我只想在数字中间有一个破折号......
  • 是否需要在固定位置插入破折号,即破折号始终插入到索引 2 处?
  • 是和不是。我只需要在edittext中插入一个破折号(在数字中间)。我不知道它只能在索引2上......
  • 换句话说:可以验证EditText live - 当输入文本时?

标签: android validation android-layout zipcode


【解决方案1】:

当用户输入邮政编码时,您可以使用TextWatcher 插入破折号。下面的例子是在索引 2 处插入一个破折号。

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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().contains("-") && s.length() > 2) {
                s.insert(2, "-");
            }

        }
});

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    相关资源
    最近更新 更多