android - 如何使编辑文本前缀不可编辑

标签 android

<分区>

我需要允许用户在 + 之后输入电话号码,我如何在编辑文本中添加这个“+”。用户无法编辑 +。用户可以输入数字后跟 +。 通过使用 editText.setText("+"); 它仍然允许用户编辑这个 +。如何使此文本不可编辑。

最佳答案

用你的类自定义 EditText。

找到下面的示例代码以供引用。

public class CustomEdit extends EditText {

    private String mPrefix = "+"; // can be hardcoded for demo purposes
    private Rect mPrefixRect = new Rect(); // actual prefix size

    public CustomEdit(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();
    }
}

在xml中使用如下

<com.example.CustomEdit
            android:id="@+id/edt_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/edit_gray"
            android:textSize="@dimen/text_14sp"
            android:inputType="number"
            android:maxLength="10"
            >

关于android - 如何使编辑文本前缀不可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35311973/

相关文章:

android - 带有自动滚动 android 的 Viewpager

Android:listview 中的 inflater 是什么?

android - 如何在 Android 中使用自定义屏幕而不是默认启动屏幕?

java - 如何使用Android Studio实现自动建议UI?

java - android on Text Change Listener

android - 在 Facebook SDK 4 (Android) 中创建请求

android - 如何将 Amazon Cognito 与适用于 Android 的 Google Plus 集成?

java - AlertDialog 再次打开

android - 我如何让android布局重绘?

Android 上的 java.lang.ClassNotFoundException : net. sourceforge.jtds.jdbc.Driver