Android 如何将编辑文本前缀设置为不可编辑

Android 如何将编辑文本前缀设置为不可编辑,android,Android,我需要允许用户在+之后输入电话号码,我知道如何在编辑文本中添加此“+”。用户无法编辑+。用户可以输入后跟+的数字。 使用editText.setText(“+”)它仍然允许用户编辑此+。如何使此文本不可编辑。在类中自定义编辑文本 查找以下示例代码以供参考 public class CustomEdit extends EditText { private String mPrefix = "+"; // can be hardcoded for demo purposes pr

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

在类中自定义编辑文本

查找以下示例代码以供参考

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"
            >

使用
TextWatcher
您可以使之成为可能。在
TextWatcher
中,您可以处理编辑文本值的操作。看这个

应该是这样的

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

        edt.setText("+");
        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().contains("+")){
                        edt.setText("+");
                        Selection.setSelection(edt.getText(), edt.getText().length());

                    }

                }
            });

您尝试了什么?@ρцσѕρєK我使用etPhone.setText(“+”,TextView.BufferType.EDITABLE)进行了尝试;但这将使编辑文本可编辑。是否有方法在xml文件中执行此操作?您可以在xml中添加此自定义编辑文本,并根据需要设置数据