我试图在显示软键盘时捕获“后退”键事件.
我正在使用SDK ver 8并且只能在软键盘为HIDDEN时成功捕获后退键事件,如下所示:
@Override public void onBackPressed() { // do something super.onBackPressed(); }
问题是系统在显示软键盘时没有调用此方法.我试图登录KeyDown / Up()方法以及上面的方法来解决这个场景中发生的事情无济于事.见下文:
@Override public boolean onKeyUp(int keyCode,KeyEvent event) { //DEBUGGING Log.d(TAG + "KeyUP",String.valueOf(event)); }
按预期返回音量和菜单键的日志,但只有在隐藏软键盘和菜单时才会记录后退键.
是否有任何“背键”大师可以解释这种现象?
任何帮助是极大的赞赏.
解决方法
以下是捕获按键事件的方法:
1.扩展editText视图以覆盖onKeyPreIme
1.扩展editText视图以覆盖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; } }
> xml中的ChatEditText
<com.test.test.ChatEditText android:id = "@+id/messageEditText" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "bottom" android:layout_marginLeft = "12dp" android:layout_marginRight = "30dp" android:background = "@null" android:hint = "Type your message" android:inputType = "textMultiLine" android:singleLine = "false" android:textColorHint = "#c4c0bd" android:textSize = "18sp"/>
>然后从任何地方附加一个监听器:
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 } }});