Android OnTouchListener安排一个线程来定位光标

Way*_*ail 0 android cursor-position ontouchlistener android-edittext

答案发布在" 在Android EditText中如何在设置后在OnTouchListener中获取光标位置 "表示将来可以为100MS安排一个线程,以便给Android时间更新EditText光标位置.没有提供关于如何实现这一目标的代码.我使用Toast尝试了以下测试代码来显示光标位置.更新触摸后不显示光标位置.有人可以更正此代码,以便在mText.setSelection(光标)中提供触摸位置吗?

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);
Run Code Online (Sandbox Code Playgroud)

Way*_*ail 5

我放弃了安排未来的线程,让Android时间更新光标位置.我找到了一种更好的方法来抑制软键盘,并且仍然可以在EditText框中显示闪烁的光标.我编写了一个onTouchListener并返回true以禁用键盘而不是使用"mText.setInputType(InputType.TYPE_NULL)".然后我必须从动作事件中获取触摸位置以将光标设置到正确的位置.

这是我使用的代码:

  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);
Run Code Online (Sandbox Code Playgroud)