美文网首页
Android将光标移至文字末尾

Android将光标移至文字末尾

作者: gbook | 来源:发表于2019-03-25 19:59 被阅读0次

摘要:本文主要是介绍在Android的EditText中如何将光标移至文字末尾端,以方便用户进行删除和修改文本信息,下面通过实例进行逐一讲解(转自云书)。

1、实现方法

可以用 setSelection() 方法来实现文本定位到尾端的功能。

2、实现代码如下

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.act_test);

    EditText etx = (EditText) findViewById(R.id.etx);

    // 更新内容

    String content = "hello world";

    etx.setText(content); // 设置文本内容

    if (content != null && !content.equals("")) {

        转自云书

        etx.setSelection(content.length()); // 将光标移至文字末尾

    }

}

3、异常处理

如果设置中对EditText组件设置了etx.setFocusable(false),那么我们则需要重新获取焦点。

方法如下:

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.act_book);

    EditText etx = (EditText) findViewById(R.id.etx);

    // 更新内容

    String content = "yun book";

    etx.setText(content); // 设置文本内容

    if (content != null && !content.equals("")) {

        etx.setSelection(content.length()); // 将光标移至文字末尾

    }

    etx.setFocusable(ture);

    etx.setFocusableInTouchMode(true);

    etx.requestFocus();

}

相关文章

网友评论

      本文标题:Android将光标移至文字末尾

      本文链接:https://www.haomeiwen.com/subject/sutivqtx.html