How to make text editing prefix inaccessible for editing

I need to allow the user to enter the phone number after +, I how to add this '+' to the editing text. User cannot edit +. The user can enter a number followed by +. Using editText.setText("+");, it will still allow the user to edit this +. How to make this text inaccessible for editing.

+4
source share
3 answers

Customize EditText with your class.

find the code example below for reference.

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

In xml use as below

<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"
            >
+4
source

TextWatcher, . TextWatcher .

0

It should be like

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());

                    }

                }
            });
0
source

Source: https://habr.com/ru/post/1628095/


All Articles