Android key event for back key when soft keyboard is shown?

前端 未结 3 694
别那么骄傲
别那么骄傲 2021-01-02 04:35

I am trying to capture the \"back\" key event when the soft keyboard is shown.

I am using SDK ver 8 and can successfully capture the back key event ONLY when the sof

3条回答
  •  迷失自我
    2021-01-02 04:57

    Here is the way to capture back press key event: 1. Extend editText view to override onKeyPreIme

    package com.test.test;
    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.KeyEvent;
    import android.widget.EditText;
    
    /**
     * Created by sumit.saurabh on 11/10/16.
     */
    public class ChatEditText extends EditText
    {
        /* Must use this constructor in order for the layout files to instantiate the class properly */
        public ChatEditText(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            // TODO Auto-generated constructor stub
        }
    
        private KeyImeChange keyImeChangeListener;
    
        public void setKeyImeChangeListener(KeyImeChange listener)
        {
            keyImeChangeListener = listener;
        }
    
        public interface KeyImeChange
        {
            public void onKeyIme(int keyCode, KeyEvent event);
        }
    
        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event)
        {
            if (keyImeChangeListener != null)
            {
                keyImeChangeListener.onKeyIme(keyCode, event);
            }
            return false;
        }
    }
    
    1. ChatEditText in xml

          
      
    2. Then attach a listener (setKeyImeChangeListener) to the edit text:

      private ChatEditText messageEditText;
      messageEditText =
         (ChatEditText) findViewById(R.id.messageEditText);
      
      messageEditText.setKeyImeChangeListener(new ChatEditText.KeyImeChange(){
          @Override
          public void onKeyIme(int keyCode, KeyEvent event)
          {
              if (KeyEvent.KEYCODE_BACK == event.getKeyCode())
              {
                  // do something
              }
          }});
      

提交回复
热议问题