4

I need to allow the user to enter the phone number after +, I how to add this '+' in edit text.User can't edit +. A user can enter the number followed by +. By using editText.setText("+"); it will still allow the user to edit this +. How to make this text as not editable.

Archana
  • 378
  • 3
  • 17

3 Answers3

5

Custom the EditText with your class.

find the below sample code 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 like 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"
            >
Maheshwar Ligade
  • 6,709
  • 4
  • 42
  • 59
0

Using TextWatcher you can make it possible . In TextWatcher you can able to handle editing text value . look this Tutorial

KDeogharkar
  • 10,939
  • 7
  • 51
  • 95
0

It should be like this

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

                    }

                }
            });
Rasel
  • 5,488
  • 3
  • 30
  • 39