How to make part of text in EditText non-removable when using RedMadRobot's input-mask-android?

1.1k views Asked by At

I am using RedMadRobot's input-mask-android library to set input mask to EditText for entering phone numbers.

public class MainActivity extends AppCompatActivity {

    static String INPUT_MASK_PHONE = "{998} [00] [000]-[00]-[00]";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText login = (EditText) findViewById(R.id.login);

        MaskedTextChangedListener maskedTextChangedListener = new MaskedTextChangedListener(
                INPUT_MASK_PHONE,
                true,
                login,
                null,
                new MaskedTextChangedListener.ValueListener() {
                    @Override
                    public void onTextChanged(boolean b, @NotNull String s) {

                    }
                }
        );

        login.addTextChangedListener(maskedTextChangedListener);
        login.setSelection(login.length());

    }

}

I am setting '998', which should not be removed when user tries remove. Now '998' can be removed.

<EditText
    android:id="@+id/login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:text="998"/>

How to make '998' not removable?

1

There are 1 answers

1
Sreehari On

Try out this sample

private final String mMobileInitial ="+974 ";
EditText login = (EditText) findViewById(R.id.login);
login.setText(mMobileInitial);
Selection.setSelection(login.getText(), login.getText().length());
        login.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(!s.toString().startsWith(mMobileInitial)){
                    login.setText(mMobileInitial);
                    Selection.setSelection(login.getText(), login.getText().length());
                }
            }
        });