代码之家  ›  专栏  ›  技术社区  ›  Mr.Eddart

结尾带有固定字符的可编辑文本

  •  -1
  • Mr.Eddart  · 技术社区  · 7 年前

    我有一个编辑文本来输入一个表示百分比的数字。

    我希望它在用户介绍的数字之后显示符号“%”。

    当用户点击1时,editText应该显示“1%”。 等等。

    如何才能做到这一点?

    非常感谢你。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Mithun Sarker Shuvro    7 年前

    添加文本更改侦听器并在中修改文本 afterTextChanged 方法,如下所示,首先移除 %

    editText.addTextChangedListener(new TextWatcher() {
    
       @Override
       public void afterTextChanged(Editable s) {
           editText.setText(s.getText().toString().replaceAll("%", "")+"%");
           editText.setSelection(editText.getText().length()-1) // just reset the cursor position before %
       }
    
       @Override    
       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }
    
       @Override    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {
    
       }
      });