How to have fixed cursor position for EditText?

2019-07-18 12:20发布

问题:

I don't want the user to insert anything in the middle of the EditText box. I only want to allow the user to click on the EditText box to bring out the keyboard, and insert at the end of the EditText box.

Is there a way to disable the ability for the user to change the cursor position when clicking on the EditText box?

I don't mind if the answer if done in XML or Java.

Thank you :)

Edit: if I have to use setSelection, is there a way to detect when the EditText box is clicked? so that I can set the cursor back to the end when the user click on the EditText.

回答1:

You can apply this trick, This worked for me. Just disable the cursor from edittext and on its click listener add your code that will keep the cursor on right most.

Here is code that i tried.

<EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:text="12"
        android:background="@color/white"
        android:padding="@dimen/activity_margin_10"
        /> 

Java Code

EditText mEditText;

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

        mEditText = (EditText)findViewById(R.id.edit);  // Initialzation of Edittext
        mEditText.setSelection(mEditText.getText().length()); // After initialization keep cursor on right side
        mEditText.setCursorVisible(false);  // Disable the cursor.

        /*
        Add Click listener and on put your code that will keep cursor on right side
         */
        mEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditText.setSelection(mEditText.getText().length());
            }
        });
}

Hope it will help you.



回答2:

Use setSelection to set the cursor position. But that won't lock the insertion point. You can tell if someone changes the selection if you create a custom view and subclass EditText to override setSelectionChanged to force a different change to your liking. You may also want to override onTextChanged to verify that any change that happens does not break your rules.



回答3:

To insert at the end of the EditText box.

you just need to set gravity to the right

android:gravity="right"

Is there a way to disable the ability for the user to change the cursor position by clicking on the EditText box?

You can use either the xml attribute android:cursorVisible="false" or the java function setCursorVisible(false).