• Google自带键盘和华为部分手机键盘的del删除键无响应EditText里设置的setOnKeyListener事件的解决方法


    1.自定义KeyDelEditText

      public class KeyDelEditText extends EditText {

        private OnKeyListener mKeyListener;

        public KeyDelEditText(Context context) {
          super(context);
        }

        public KeyDelEditText(Context context, AttributeSet attrs) {
          super(context, attrs);
        }

        public KeyDelEditText(Context context, AttributeSet attrs, int defStyle) {
          super(context, attrs, defStyle);
        }

        @Override
        public void setOnKeyListener(OnKeyListener l) {
          mKeyListener = l;
          super.setOnKeyListener(l);
        }

        @Override
        public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
          return new InnerInputConnection(super.onCreateInputConnection(outAttrs), true);
        }

        private class InnerInputConnection extends InputConnectionWrapper {

          public InnerInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
          }

          @Override
          public boolean deleteSurroundingText(int beforeLength, int afterLength) {
            boolean ret = false;
            if (beforeLength == 1 && afterLength == 0 && mKeyListener != null) {
              ret = mKeyListener.onKey(KeyDelEditText.this, KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
            }
            return ret || super.deleteSurroundingText(beforeLength, afterLength);
          }
        }

      }

    2.替换xml里面的EditText为KeyDelEditText

      <com.suyf.view.KeyDelEditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    3.正常方式设置setOnKeyListener事件

      EditText etContent = findViewById(R.id.et_content);

      etContent.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

          if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
            //处理具体的删除操作
            return true;
          }
          return false;

        }

      });

    和一般的正常情况相比较,修改很少,只需要引入KeyDelEditText这个类,并替换xml文件里面的EditText为KeyDelEditText即可,其他的都不用改动。

  • 相关阅读:
    java_doc
    zai~~myGODDDD
    get span time
    someThing about thread
    互斥
    http://www.vchelp.net/services/about_us/itbookreview_intro.asp
    (十三)sealed、new、virtual、abstract 和 override java程序员
    (15) 常用基础知识 java程序员
    (14)abstract class 和 interface java程序员
    (16) 结构和类 java程序员
  • 原文地址:https://www.cnblogs.com/yongfengnice/p/7657222.html
Copyright © 2020-2023  润新知