有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Android中移动EditText中的光标

我想用自定义的左键和右键在EditText中移动光标。当我点击左键时,它应该向左移动一个字符,当我点击右键时,它应该向右移动一个字符


共 (1) 个答案

  1. # 1 楼答案

    我为它创建了一个简单的项目。要移动光标,只需使用以下函数:editText.setSelection(position)。但是在调用这个函数之前,你必须检查你是否在开始/结束,因为你可以得到异常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>