在EditText中放置常量文本,该文本应该是不可编辑的 - Android

时间:2013-01-07 11:41:16

标签: android textview android-edittext

我希望在editText中有一个常量文本,如:

http://<here_user_can_write>

用户不应该删除“http://”中的任何字符,我搜索了这个并发现了这个:

editText.setFilters(new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence src, int start,
            int end, Spanned dst, int dstart, int dend) {
            return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
        }
    }
}); 

但我不知道它是否限制用户不从开始到结束限制删除任何字符。我也无法理解Spanned类的使用。

如果我们可以将TextView置于EditText内,那么一种方法将是一个不错的选择,但我不认为它在Android中是可行的,因为两者都是视图,是否可能?

16 个答案:

答案 0 :(得分:116)

你尝试过这种方法吗?

final EditText edt = (EditText) findViewById(R.id.editText1);

edt.setText("http://");
Selection.setSelection(edt.getText(), edt.getText().length());


edt.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(!s.toString().startsWith("http://")){
                edt.setText("http://");
                Selection.setSelection(edt.getText(), edt.getText().length());

            }

        }
    });

答案 1 :(得分:13)

您可以使用InputFilter

实际执行此操作
final String prefix = "http://"
editText.setText(prefix);

editText.setFilters(new InputFilter[] {
    new InputFilter() {
      @Override
      public CharSequence filter(final CharSequence source, final int start,
          final int end, final Spanned dest, final int dstart, final int dend) {
        final int newStart = Math.max(prefix.length(), dstart);
        final int newEnd = Math.max(prefix.length(), dend);
        if (newStart != dstart || newEnd != dend) {
          final SpannableStringBuilder builder = new SpannableStringBuilder(dest);
          builder.replace(newStart, newEnd, source);
          if (source instanceof Spanned) {
            TextUtils.copySpansFrom(
                (Spanned) source, 0, source.length(), null, builder, newStart);
          }
          Selection.setSelection(builder, newStart + source.length());
          return builder;
        } else {
          return null;
        }
      }
    }
});

如果您还希望不能选择前缀,可以添加以下代码。

final SpanWatcher watcher = new SpanWatcher() {
  @Override
  public void onSpanAdded(final Spannable text, final Object what,
      final int start, final int end) {
    // Nothing here.
  }

  @Override
  public void onSpanRemoved(final Spannable text, final Object what, 
      final int start, final int end) {
    // Nothing here.
  }

  @Override
  public void onSpanChanged(final Spannable text, final Object what, 
      final int ostart, final int oend, final int nstart, final int nend) {
    if (what == Selection.SELECTION_START) {
      if (nstart < prefix.length()) {
        final int end = Math.max(prefix.length(), Selection.getSelectionEnd(text));
        Selection.setSelection(text, prefix.length(), end);
      }
    } else if (what == Selection.SELECTION_END) {
      final int start = Math.max(prefix.length(), Selection.getSelectionEnd(text));
      final int end = Math.max(start, nstart);
      if (end != nstart) {
        Selection.setSelection(text, start, end);
      }
    }
  }
};

editText.getText().setSpan(watcher, 0, 0, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

答案 2 :(得分:9)

@Rajitha Siriwardena的答案出现了轻微的问题。 如果你有字符串

,它假定在后缀之前删除了除后缀之外的整个字符串
http://stackoverflow.com/

并尝试删除http://您要删除stackoverflow.com/的{​​{1}}的任何部分,结果只会http://

我还添加了一个检查,用户试图在前缀之前输入。

 @Override
 public void afterTextChanged(Editable s) {
     String prefix = "http://";
     if (!s.toString().startsWith(prefix)) {
         String cleanString;
         String deletedPrefix = prefix.substring(0, prefix.length() - 1);
         if (s.toString().startsWith(deletedPrefix)) {
             cleanString = s.toString().replaceAll(deletedPrefix, "");
         } else {
             cleanString = s.toString().replaceAll(prefix, "");
         }
         editText.setText(prefix + cleanString);
         editText.setSelection(prefix.length());
    }
}

注意:这并不能处理用户仅在之前和之后尝试编辑前缀的情况。

答案 3 :(得分:5)

将自定义前缀添加到您的EDITTEXT(前缀不可编辑)的代码

来自Ali Muzaffar的媒体代码

public class PrefixEditText extends AppCompatEditText {
    float originalLeftPadding = -1;

    public PrefixEditText(Context context) {
        super(context);
    }

    public PrefixEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PrefixEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        calculatePrefix();
    }

    private void calculatePrefix() {
        if (originalLeftPadding == -1) {
            String prefix = (String) getTag();
            float[] widths = new float[prefix.length()];
            getPaint().getTextWidths(prefix, widths);
            float textWidth = 0;
            for (float w : widths) {
                textWidth += w;
            }
            originalLeftPadding = getCompoundPaddingLeft();
            setPadding((int) (textWidth + originalLeftPadding),
                getPaddingRight(), getPaddingTop(),
                getPaddingBottom());
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        String prefix = (String) getTag();
        canvas.drawText(prefix, originalLeftPadding, getLineBounds(0, null), getPaint());
    }
}

和XML

<com.yourClassPath.PrefixEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom"
    android:textSize="14sp"
    android:tag="€ " />

答案 4 :(得分:4)

你几乎是对的,试试

private final String PREFIX="http://";

editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int
                    dend) {
                return dstart<PREFIX.length()?dest.subSequence(dstart,dend):null;
            }
        }});

答案 5 :(得分:4)

  

摘自Ali Muzaffar的博客,请参阅the original post了解更多详情。

使用自定义EditText视图绘制前缀文本并根据前缀文本大小添加填充:

public class PrefixEditText extends EditText {

private String mPrefix = "$"; // add your prefix here for example $
private Rect mPrefixRect = new Rect(); // actual prefix size

public PrefixEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
    mPrefixRect.right += getPaint().measureText(" "); // add some offset

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
}

@Override
public int getCompoundPaddingLeft() {
    return super.getCompoundPaddingLeft() + mPrefixRect.width();
}
}

答案 6 :(得分:1)

我知道我已经恢复了一个旧帖子,但是我想与社区分享这些天我一直在努力解决这个话题,我发现在TextView上放置EditText是不仅是完美可行的(回答问题的第二部分),在这种情况下,当在起始位置需要常量文本时更多,但也是优选的。此外,光标甚至在&#34; mutable&#34;之前都不会移动。文字根本就是优雅的效果。 我更喜欢这个解决方案,因为它不会给我的应用程序增加工作量和复杂性,无论是听众还是其他人。

以下是我的解决方案的示例代码:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginStart="3dp"
        android:text="http://" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textUri"
        android:paddingStart="choose an appropriate padding" />
</RelativeLayout>

通过将视图封闭在RelativeLayout中,它们将重叠。 这里的诀窍是使用android:paddingStart的{​​{1}}属性,使文本在EditText之后立即开始,而TextViewandroid:layout_centerVertical="true"属性android:layout_marginStart="3dp"确保其文本与输入的文本以及TextView的基础行的开头正确对齐(或者至少在使用材料主题时发生这种情况)。

答案 7 :(得分:1)

这基本上是在电话号码的编辑文本字段中添加前缀“ +91”。

1。将此代码添加到活动的oncreate()

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

   // Write other things......//

   etPhoneNumber.setFilters(new InputFilter[]{getPhoneFilter(),newInputFilter.LengthFilter(13)});

    etPhoneNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                if (etPhoneNumber.getText().toString().isEmpty()) {
                    etPhoneNumber.setText("+91");
                    Selection.setSelection(etPhoneNumber.getText(), etPhoneNumber.getText().length());                    }
            } else {
                if (etPhoneNumber.getText().toString().equalsIgnoreCase("+91")) {
                    etPhoneNumber.setFilters(new InputFilter[]{});
                    etPhoneNumber.setText("");
                    etPhoneNumber.setFilters(new InputFilter[]{getPhoneFilter(),new InputFilter.LengthFilter(13)});

                }
            }
        }
    });
}

2。声明一个名为getPhoneFilter()的方法

    private InputFilter getPhoneFilter() {

    Selection.setSelection(etPhoneNumber.getText(), etPhoneNumber.getText().length());

    etPhoneNumber.addTextChangedListener(new TextWatcher() {

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

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

        @Override
        public void afterTextChanged(Editable s) {
            if(!s.toString().startsWith("+91")){
                if (etPhoneNumber.getFilters() != null && etPhoneNumber.getFilters().length > 0) {
                    etPhoneNumber.setText("+91");
                    Selection.setSelection(etPhoneNumber.getText(), etPhoneNumber.getText().length());
                }
            }
        }
    });

     // Input filter to restrict user to enter only digits..
    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 (!String.valueOf(getString(R.string.digits_number)).contains(String.valueOf(source.charAt(i)))) {
                    return "";
                }
            }
            return null;
        }
    };
    return filter;
}

3。在值文件中声明“ digits_number”

    <string name="digits_number">1234567890+</string>

答案 8 :(得分:1)

基于@demaksee条评论。我扩展了EditText并覆盖了onSelectionChanged函数。因此用户甚至无法编辑前缀。非常简单实用。 科特林:

private var prefix : String? = ""

override fun onSelectionChanged(selStart: Int, selEnd: Int) {
    if (prefix != null && prefix!!.isNotBlank()) {
        var finalStart = selStart
        var finalEnd = selEnd

        val prefixLength = prefix!!.length
        if (prefixLength > selStart) {
            finalStart = prefixLength
        }

        if (prefixLength > selEnd) {
            finalEnd = prefixLength
        }

        if (finalStart == selStart && finalEnd == selEnd) {
            super.onSelectionChanged(finalStart, finalEnd)
        } else {
            val startWithPrefix = text?.startsWith(prefix ?: "") ?: prefix.isNullOrBlank()
            if (!startWithPrefix) {
                setText(prefix)
            }

            setSelection(finalStart, finalEnd)
        }
    }
}

public fun setPrefix(prefix: String) {
    editText.setText(prefix)
    editText.setSelection(prefix.length)
    this.prefix = prefix
}

答案 9 :(得分:1)

1.2.0-alpha01material design library版本开始,文本字段支持前缀和后缀:

<com.google.android.material.textfield.TextInputLayout
        app:prefixText="Price: "
        app:prefixTextAppearance="..."
        app:prefixTextColor="..."
        app:suffixText="Dollar"
        app:suffixTextColor="..."
        app:suffixTextAppearance="...">

    <com.google.android.material.textfield.TextInputEditText .../>

</com.google.android.material.textfield.TextInputLayout>

我认为后缀有一个缺点,即后缀固定在文本字段的末尾,并且不随输入文本一起流动。

答案 10 :(得分:1)

我制作了Kotlin扩展功能,用于为EditText添加前缀

fun EditText.addPrefix(prefix: String) {
        var text = ""
        var isPrefixModified = false
        val formattedPrefix = "$prefix "
        var lastCharSequence: CharSequence? = null

        val setEditText: () -> Unit = {
            setText(text)
            Selection.setSelection(editableText, text.length)
        }

        this.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable?) {
                val newText = editable.toString()

                when {
                    isPrefixModified -> {
                        isPrefixModified = false
                        setEditText()
                    }
                    isTryingToDeletePrefix(newText) -> {
                        setEditText()
                    }
                    isNewInput(newText) -> {
                        text = "$formattedPrefix$newText"
                        setEditText()
                    }
                    else -> {
                        text = newText
                    }
                }
            }

            override fun beforeTextChanged(charSequence: CharSequence?, start: Int,
                                           count: Int, after: Int) {
                charSequence?.let {
                    if (it != lastCharSequence && it.isNotEmpty() && start <= prefix.length) {
                        isPrefixModified = true
                    }
                    lastCharSequence = charSequence
                }
            }

            override fun onTextChanged(charSequence: CharSequence?, start: Int,
                                       before: Int, count: Int) {
                // Ignore
            }

            private fun isTryingToDeletePrefix(newText: String) =
                    text.isNotEmpty() && newText.length < text.length && isNewInput(newText)

            private fun isNewInput(newText: String) = !newText.contains(formattedPrefix)
        })
    }

答案 11 :(得分:0)

这是一个效率较低的解决方案,应该处理在前缀中删除/插入字符或单词时的所有情况。

prefix = "http://"
extra = "ahhttp://"
differencePrefix(prefix, extra) = "aht"

代码:

public static String differencePrefix(String prefix, String extra) {
    if (extra.length() < prefix.length()) return "";
    StringBuilder sb = new StringBuilder();
    StringBuilder eb = new StringBuilder();
    int p = 0;
    for (int i = 0; i < extra.length(); i++) {
        if (i >= prefix.length()) {
            while(p < extra.length()) {
                eb.append(extra.charAt(p));
                p++;
            }
            break;
        }
        if (p >= extra.length()) break;
        char pchar = extra.charAt(p);
        char ichar = prefix.charAt(i);
        while(pchar != ichar) {
            //check if char was deleted
            int c = i + 1;
            if (c < prefix.length()) {
                char cchar = prefix.charAt(c);
                if (cchar == pchar) {
                    break;
                }
            }
            sb.append(pchar);
            p++;
            if (p >= extra.length()) break;
            pchar = extra.charAt(p);
        }
        p++;
    }

    return eb.toString() + sb.toString();
}

您可以像这样使用

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) {
        String input = s.toString();
        if (!input.startsWith(prefix)) {
            String extra = differencePrefix(prefix, input);
            String newInput = prefix + extra;
            editText.setText(newInput);
            editText.setSelection(newInput.length());
        }
    }
});

答案 12 :(得分:0)

我刚刚找到了解决方法如何使前缀不可编辑以及如果尝试删除前缀如何保存文本。这与@Rajitha Siriwardena的回答非常接近。您错过的只是在应用任何更改之前保存文本。它将在afterTextChanged(...)中恢复。

代码:

final String prefix = "http://";
editText.setText(prefix);
Selection.setSelection(editText.getText(), editText.getText().length());

editText.addTextChangedListener(new TextWatcher() {
    String text;
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        text = charSequence.toString();
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (!editable.toString().startsWith(prefix)) {
            editText.setText(text);
            Selection.setSelection(editText.getText(), editText.getText().length());
        }
    }
});

答案 13 :(得分:0)

    EditText msg=new EditText(getContext());
                msg.setSingleLine(true);
                msg.setSingleLine();
                msg.setId(View.generateViewId());
                msg.measure(0,0);



                TextView count=new TextView(getContext());
                count.setTextColor(Color.parseColor("#666666"));
                count.setText("20");
                count.setPadding(0,0,(int)Abstract.getDIP(getContext(),10),0);
                count.measure(0,0);
float tenPIX =TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10,getContext().getResources().getDisplayMetrics());

 msg.setPadding((int)tenPIX,(int)tenPIX,(int)(int)tenPIX+count.getMeasuredWidth(),(int)tenPIX);


                RelativeLayout ll1=new RelativeLayout(getContext());
                ll1.addView(msg,new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

LayoutParams countlp=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                countlp.addRule(RelativeLayout.ALIGN_END,msg.getId());
                countlp.addRule(RelativeLayout.ALIGN_BASELINE,msg.getId());
                ll1.addView(count,countlp);

答案 14 :(得分:0)

以下代码对我有用。它处理以下情况:用户编辑前缀,删除前缀,从缓冲区插入文本,更改所选文本。如果用户更改了前缀,则焦点将移到前缀的末尾。

    final String prefix = "http://";
    final String[] aLastText = {prefix};
    et.setText(prefix);
    et.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void afterTextChanged(Editable sNew) {

            if (!sNew.toString().startsWith(prefix)) {
                String sLast = aLastText[0];
                boolean isRemoving = sNew.length() < sLast.length();

                int start;
                int end = sNew.length() - 1;
                for (start = 0; start < sLast.length() && start < sNew.length(); start++) {
                    if (sLast.charAt(start) != sNew.charAt(start)) 
                        break;
                }
                int k = sLast.length() - 1;
                for (; end >= start && k >= 0; end--, k--) {
                    if (sLast.charAt(k) != sNew.charAt(end)) 
                        break;
                }
                String sEdited = sNew.toString().substring(start, ++end);
                k += isRemoving ? 1 : 0;
                k = k < prefix.length() ? prefix.length() : k;
                String sSuffix = sLast.substring(k, sLast.length());

                et.setText(prefix + sEdited + sSuffix);
                et.setSelection(et.getText().length() - sSuffix.length());
            }
            aLastText[0] = et.getText().toString();
        }
    });

示例:

ht5tp:// localhost,5http:// localhost,http:/ 5 / localhost-> http://5localhost

http:localhost-> http://localhost

答案 15 :(得分:0)

为此目的,易于使用的Kotlin扩展功能

fun EditText.stickPrefix(prefix: String) {
    this.addTextChangedListener(afterTextChanged = {
        if (!it.toString().startsWith(prefix) && it?.isNotEmpty() == true) {
            this.setText(prefix + this.text)
            this.setSelection(this.length())

        }
    })
}
//someEditText.stickPrefix("+")