2

在我的应用程序中,我有 EditText 元素,但我像 TextView 一样使用它(它不可编辑)。

我想通过单击某个按钮来选择该字段中的所有文本。我用下一个代码来做

Selection.setSelection((Spannable) et.getText(),0, et.getText().length());
et.setSelected(true);

它工作正常并选择了文本,但之后我无法更改选择的结束。如何以编程方式调用选择句柄?

我也阻止了 OnLongClick,因为我只需要复制选项并将其添加到自定义按钮中。

4

3 回答 3

2

您需要确保在布局文件中EditText具有该属性。android:textIsSelectable="true"

你也可以做同样的事情 et.setTextIsSelectable(true);

但请确保您的应用程序 minSdkVersion使用11它。

于 2013-04-22T10:26:35.560 回答
0

尝试这样的事情

 et.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
            int strt=   et.getSelectionStart();
            int end =   et.getSelectionEnd();
                Log.i(" Selectionm",et.getText().toString().substring(strt, end));
                return false;
            }
        });
于 2013-04-22T10:23:09.280 回答
0

使用 required android:textIsSelectable="true",使用 EditText 或 TextView 作为参数调用以下方法:

private fun forceSelectionWithHandlesVisible(view: TextView) {
    if (!view.hasSelection()) {
        view.performLongClick()
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
        // Hack required to make the selection handles visible when focus programmatically
        val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_UP, 0F, 0F, 0)
        with(event) {
            view.onTouchEvent(this)
            recycle()
        }
    }
}

为我工作。

于 2020-08-26T16:39:43.307 回答