Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

android: How to get text position from touch event

I'm wanting to implement a custom text interface, with touch+drag selecting text and the keyboard not being raised, in contrast to the default behavior of a long-click bringing up the CCP menu and the keyboard. My understanding suggests I need this approach:

onTouchEvent(event){
  case touch_down:
    get START text position

  case drag
    get END text position
    set selection range from START to END
}

I've found out all about getSelectStart() and various methods to setting a range and such, but I cannot find how to get the text position based on a touch event getX() and getY(). Is there any way to do this? I've seen the behaviour I want in other office apps.

Also, how would I stop the keyboard appearing until manually requested?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"mText.setInputType(InputType.TYPE_NULL)" will suppress the soft keyboard but it also disables the blinking cursor in an EditText box under Android 3.0 and above. I coded an onTouchListener and returned true to disable the keyboard and then had to get the touch position from the motion event to set the cursor to the correct spot. You might be able to use this on an ACTION_MOVE motion event to select text for dragging.

Here is the code I used:

  mText = (EditText) findViewById(R.id.editText1);
  OnTouchListener otl = new OnTouchListener() {
  @Override
  public boolean onTouch(View v, MotionEvent event) {
      switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
          Layout layout = ((EditText) v).getLayout();
          float x = event.getX() + mText.getScrollX();
          int offset = layout.getOffsetForHorizontal(0, x);
          if(offset>0)
              if(x>layout.getLineMax(0))
                  mText.setSelection(offset);     // touch was at end of text
              else
                  mText.setSelection(offset - 1);
          break;
          }
      return true;
      }
  };
  mText.setOnTouchListener(otl);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...