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.
Asked
Active
Viewed 5,449 times
4

Archana
- 378
- 3
- 17
-
What you have tried? – ρяσѕρєя K Feb 10 '16 at 10:06
-
@ρяσѕρєяK I tried by using etPhone.setText("+", TextView.BufferType.EDITABLE); But this will make the edit text to editable. – Archana Feb 10 '16 at 10:08
3 Answers
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
-
-
You can add this Custom editText in your xml and set the data what you want – Maheshwar Ligade Feb 10 '16 at 10:09
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