如何在EditText中单击文本来放置光标?

问题描述 投票:0回答:2

我正在尝试设置EditText,以便用户可以将光标放置在EditText中所需的随机位置,以便可以修改部分文本。我也希望光标可见。

有Java代码解决方案-> Set cursor position in edittext according to user click

没有XML属性来完成此操作吗?

android android-edittext android-sdk-2.3
2个回答
0
投票
EditText editText = findViewById(R.id.editText); editText.setSelection(3); // Custom point Cursor

如果您希望用户能够使用光标,则只需将光标最后设置为一个好习惯:

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length()); // End point Cursor

如果要使用XML并将其定义为属性,则需要确定它是静态的还是取决于用户:

如果是静态的,然后使用以下属性

android.selection

如果不是静态的并且依赖于用户

在这种情况下,您需要将

[XML layout file与相应的

ViewController绑定,该绑定可以是ActivityFragment,并且设置布局文件可以读取的Int值。


0
投票

现在在res/values/attrs.xml

<resources> <declare-styleable name="MyCustomEditText"> <attr name="cursor_position" format="string" /> </declare-styleable> </resources>

在xml布局中使用自定义edittext

<org.example.yourpackage.CustomEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:cursor_position="5" //it can be any index you want ..........

自定义编辑文本

class CustomEditText extends EditText { public CustomEditText(Context context) { super(context); } public CustomEditText(Context context, AttributeSet attrs) { super(context, attrs); } public CustomEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //get attribute of cursor_position TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomEditText, defStyle, 0); String index = a.getString(R.styleable.MyCustomEditText_cursor_position); //set the cursor index this.setSelection(Integer.parseInt(index)); } }

© www.soinside.com 2019 - 2024. All rights reserved.