【问题标题】:Prefilled text in edittext在edittext中预填充文本
【发布时间】:2015-09-23 08:24:36
【问题描述】:

我想在手机号码的编辑文本中添加一个预填充的文本,例如国家代码。预填充的文本应该是不可编辑的。我已经通过覆盖 onSelectionChanged() 进行了尝试。有没有更好的解决方案?

    final EditText editText = new EditText(this){
        int prevSelection;
        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if(selStart < 4){
                setSelection(prevSelection);
                return;
            }
            prevSelection = selStart;
        }
    };

【问题讨论】:

  • setText 并将 editable 设置为 false?
  • editText.setHint("")
  • 或者只设置文本然后设置启用false
  • 发布你的 onSelectionChanged() 代码,因为它应该可以工作(你基本上想要一个前缀,对吧?)

标签: android android-edittext


【解决方案1】:

这是你想要的吗?

editText.setText("This is a prefilled text"); // This to set prefilled text
editText.setFocusable(false);                 // This disable editing

editText.setHint("This is sample country code"); // this is the hint

提示是这样的:

【讨论】:

  • 我认为他只是希望前缀始终存在,而不是禁用版本。
【解决方案2】:

试试这个

final EditText editText = new EditText(this){
        int prevSelection;
        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            if (!editText.getText().toString().startsWith("pre filled text")){
                editText.setText("pre filled text" + editText.getText().toString());
            }

        }
    };

该函数将检查 EditText 是否以“preFilled”文本开头,如果不是,则将其添加到 EditText 的开头

【讨论】:

    【解决方案3】:

    在包含EditTextActivityFragment 中实现android.text.TextWatcher

    afterTextChanged 方法中,将国家代码添加到文本的开头。

    最好在添加之前检查国家代码是否已经填写。注意不要在这里无限循环结束。

    【讨论】:

      【解决方案4】:

      尝试使用这个:

       editText.setText("country code" + editText.getText().toString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多