【问题标题】:Android getselectionStart and Getselectionend text don't workAndroid getselectionStart 和 Getselectionend 文本不起作用
【发布时间】:2013-10-24 23:16:34
【问题描述】:

谁能解释一下,我做错了什么?

在下面的这种情况下,“tt”是我的 TexView。 在我的 Oncreate() 方法中,我有:

tt = (TextView) findViewById(R.id.ni);
tt.setText("This is a try");

然后

tt.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                String vi = tt.getText().toString().substring(tt.getSelectionStart(),tt.getSelectionEnd());
                Toast.makeText(getApplicationContext(), vi,Toast.LENGTH_LONG).show();

                }

        });

Onclick 不显示任何内容。

谢谢。

【问题讨论】:

  • 看起来您缺少一些代码 - 应该更像 setOnClickListener(...) ?无论如何,尝试将操作分解为更多的语句,以便更容易调试。将 start 和 stop 放入局部变量中。还有一件事:你会得到多个 onClicks - 你怎么知道哪一个是突出显示选择的结果?使用日志文件代替 Toast - 简单的方法:System.out.println ("...stuff...");
  • 谢谢你,@PeriHartman。我想我的问题在于获取选择的方法,因为如果我替换数字方法,我的 toast 工作正常,显示子字符串。

标签: android textview getselection


【解决方案1】:

几天前我也遇到了同样的问题,最后我可以找到以下解决方案。将这个过程延迟 10 毫秒也会有帮助。将它放在您的 onClick/onLongClick 方法中,无论您要获取所选文本的任何位置。

原始答案:textView.getSelectionEnd() returning start index value on Samsung Marshmallow 6.0 devices

我希望这对将来有类似问题的人有所帮助。

new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                int startIndex = textView.getSelectionStart();
                int endIndex = textView.getSelectionEnd();

                if ((endIndex - startIndex) <= 0) {
                    return;
                }

                // UI related code here
            }
        }, TIME_IN_MS_TO_DELAY);
        return false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2019-11-07
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多