如何在EditText中单击文本来放置光标? (已解决)

时间:2020-04-22 23:52:23

标签: android android-edittext android-sdk-2.3

更新:----->解决方案

自从我问了这个问题后,我读到如果您使用命令setInputType(InputType.TYPE_NULL);禁用软键盘,那么它将禁用(闪烁的)光标。

我正在做的是使用“按钮”创建键盘布局并将其作为片段加载。 ( Android似乎不允许更改软键盘来满足某些需求。。)我想要做的是重新启用光标,以便通过点击(单击)光标可以放置在字符串中所需的位置以进行编辑。

EditText继承自TextView,(不会认为此方法将成为TextView的一部分),该方法具有一个称为setShowSoftInputOnFocus(bool);的方法。此方法将禁用软键盘而不禁用光标。


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

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

是否没有XML属性来完成此任务?

2 个答案:

答案 0 :(得分: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 绑定,该绑定可以为 {{1} } Activity ,并设置可以读取布局文件的Int值。

答案 1 :(得分:0)

如果要通过xml设置initial cursor position,请查看我的答案

也许可以创建一个自定义的EditText并在任何xml布局中重复使用,对其进行自定义以执行您想要的操作:

现在位于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));



    }
}