Mohd Naushad
Mohd Naushad

Reputation: 572

How to move cursor in EditText in Android

I want to move a cursor in EditText with custom left and right buttons. When I click the left button then it should go one character left and when I click a right button then it should go one character right.

Upvotes: 2

Views: 223

Answers (1)

iknow
iknow

Reputation: 9872

I created a simple project for it. To move cursor You just can use this function: editText.setSelection(position). But before calling this function You have to check if You are at the start/end because You can get exception java.lang.IndexOutOfBoundsException.

EditText editText;
Button buttonBackward, buttonForward;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = findViewById(R.id.editText);
    buttonBackward = findViewById(R.id.buttonBackward);
    buttonForward = findViewById(R.id.buttonForward);

    buttonForward.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if (editText.getSelectionEnd() < editText.getText().toString().length())
            {
                editText.setSelection(editText.getSelectionEnd() + 1);
            }
            else
            {
                //end of string, cannot move cursor forward
            }
        }
    });

    buttonBackward.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if (editText.getSelectionStart() > 0)
            {
                editText.setSelection(editText.getSelectionEnd() - 1);
            }
            else
            {
                //start of string, cannot move cursor backward
            }
        }
    });
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/buttonForward"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Forward" />

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

    <Button
        android:id="@+id/buttonBackward"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Backward" />

</LinearLayout>

Upvotes: 3

Related Questions