![](/img/trans.png)
[英]How to change cursor position in a multiline edittext in android?
[英]How to move cursor in EditText in Android
我想使用自定义左右按钮在EditText
中移动 cursor。 当我单击左按钮时,它应该 go 左一个字符,当我单击右键时,它应该 go 右一个字符。
我为它创建了一个简单的项目。 要移动 cursor 你可以使用这个 function: editText.setSelection(position)
。 但在调用此 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.