更新: ----->解决方案
自从我问了这个问题后,我读到如果您使用命令setInputType(InputType.TYPE_NULL);
禁用软键盘,那么它将禁用(闪烁的)光标。
我正在做的是,我使用Buttons创建了键盘布局,并将其作为片段加载。 (Android似乎不允许更改软键盘来满足某些需求。)我想要做的是重新启用光标,以便通过点击(单击)将光标定位在在字符串中所需的位置进行编辑。
EditText继承自TextView,(一个人不会认为此方法将成为TextView的一部分),它具有一个称为setShowSoftInputOnFocus(bool);
的方法。此方法将禁用软键盘而不禁用光标。
我正在尝试设置EditText,以便用户可以将光标放置在EditText中所需的随机位置,以便可以修改部分文本。我也希望光标可见。
有Java代码解决方案-> Set cursor position in edittext according to user click
没有XML属性来完成此操作吗?
如果您希望用户定义应该在何处设置光标,则应通过以下方式以编程方式进行操作:
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
绑定,该值可以为Activity
或Fragment
,并且设置布局文件可以读取的Int值。
[如果您想通过xml设置initial cursor position
,请看我的回答
现在在res/values/attrs.xml
<resources>
<declare-styleable name="MyCustomEditText">
<attr name="cursor_position" format="string" />
</declare-styleable>
</resources>
在xml布局中使用自定义edittext
<com.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));
}
}