Pregunta

The answer posted at "In Android EditText how to get the cursor position in an OnTouchListener after it is set" indicates that a thread can be scheduled for 100MS in the future to give Android time to update the EditText cursor position. There was no code provided on how this can be accomplished. I have tried the following test code using Toast to display the cursor position. It is not displaying the cursor position after updating for the touch. Can someone correct this code so the position of touch is provided in mText.setSelection(cursor)?

OnTouchListener otl = new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent evt) {
                    Runnable r = new Runnable()
                        {
                            public void run() 
                            {
                                int cursor = mText.getSelectionStart();
                                Toast.makeText(getApplicationContext(), "Cursor=" + cursor, Toast.LENGTH_SHORT).show();
                                mText.setSelection(cursor);
                            }
                        };
                        Handler handler = new Handler();
                        handler.postDelayed(r, 1500);
                        return true;
                    }
                 };
                mText.setOnTouchListener(otl);
¿Fue útil?

Solución

I gave up on scheduling a future thread to give Android time to update the cursor position. I found a better way to suppress the soft keyboard and still get a blinking cursor to display in an EditText box. I coded an onTouchListener and returned true to disable the keyboard instead of using "mText.setInputType(InputType.TYPE_NULL)". I then had to get the touch position from the motion event to set the cursor to the correct spot.

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top