简体   繁体   English

如何在 Android 中的 EditText 中移动 cursor

[英]How to move cursor in EditText in Android

I want to move a cursor in EditText with custom left and right buttons.我想使用自定义左右按钮在EditText中移动 cursor。 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.当我单击左按钮时,它应该 go 左一个字符,当我单击右键时,它应该 go 右一个字符。

I created a simple project for it.我为它创建了一个简单的项目。 To move cursor You just can use this function: editText.setSelection(position) .要移动 cursor 你可以使用这个 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 .但在调用此 function 之前,您必须检查您是否在开始/结束,因为您可以获得异常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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM