如何获得单击的跨度在Android TextView中的x,y位置?

时间:2019-05-13 11:54:46

标签: android textview ontouchevent spannable linkmovementmethod

我有一个可扩展的Textview。我想在TextView内选定范围的顶部显示弹出窗口。像这样:

enter image description here

我的代码是:

String definition = textView.getText().toString().trim();
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(definition, TextView.BufferType.SPANNABLE);

Spannable spans = (Spannable) textView.getText();
Integer[] indices = getIndices(
  textView.getText().toString(), ' ');
int start = 0;
int end = 0;

for (int i = 0; i <= indices.length; i++) {
  ClickableSpan clickSpan = getClickableSpan();
  end = (i < indices.length ? indices[i] : spans.length());
  spans.setSpan(clickSpan, start, end,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  start = end + 1;
  }

private Integer[] getIndices(String s, char c) {
int           pos     = s.indexOf(c, 0);
List<Integer> indices = new ArrayList<Integer>();
while (pos != -1) {
  indices.add(pos);
  pos = s.indexOf(c, pos + 1);
}
return (Integer[]) indices.toArray(new Integer[0]);
}

private ClickableSpan getClickableSpan() {
return new ClickableSpan() {
  @SuppressLint("ClickableViewAccessibility")
  @Override
  public void onClick(View widget) {
    TextView tv = (TextView) widget;
    final String word = tv
            .getText()
            .subSequence(tv.getSelectionStart(),
                    tv.getSelectionEnd()).toString();

    tv.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        popup(word, (int) event.getRawX(), (int) event.getRawY());
        return false;
      }
    });

  }

};
}
正如您在图片代码中看到的那样,

工作正常,但是由于在Android中onTouch之前调用了onClick,弹出窗口显示了在上一步中单击的单词。 对不起,英语不好。

1 个答案:

答案 0 :(得分:0)

要获取xy,您可以设置OnTouchListener来注册点击事件

在Java中

private void setOnTouchListener() {
    textView.setOnTouchListener((view, event) -> {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            float clickedX = event.getX();
            float clickedY = event.getY();
        }

        return false;
    });
}

在科特林

private fun setOnTouchListener() {
    text_view.setOnTouchListener { view, event ->
        if (event?.action == MotionEvent.ACTION_DOWN) {
            val clickedX = event.x
            val clickedY = event.y
        }

        false
    }
}