Java Android中如何在EditText中移动光标
我想在Java Android中如何在EditText中移动光标,java,android,android-studio,Java,Android,Android Studio,我想在EditText中使用自定义的左右按钮移动光标。当我单击左按钮时,它应该向左移动一个字符;当我单击右按钮时,它应该向右移动一个字符。我为它创建了一个简单的项目。要移动光标,只需使用以下函数:editText.setSelection(position)。但是在调用此函数之前,您必须检查您是否处于开始/结束位置,因为您可以获得异常java.lang.IndexOutOfBoundsException EditText editText; Button buttonBackward, butt
EditText
中使用自定义的左右按钮移动光标。当我单击左按钮时,它应该向左移动一个字符;当我单击右按钮时,它应该向右移动一个字符。我为它创建了一个简单的项目。要移动光标,只需使用以下函数: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
}
}
});
}
EditText;
按钮向后,按钮向前;
@凌驾
创建时受保护的void(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(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
如果(editText.getSelectionEnd()0)
{
editText.setSelection(editText.getSelectionEnd()-1);
}
其他的
{
//字符串的开头,不能向后移动光标
}
}
});
}
您能告诉我们到目前为止您已经尝试了什么吗?我已经尝试了很多,但我没有找到我必须从哪里开始
<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>