我在标签控制器中有一些意图,其中一个我有一个编辑文本,我需要知道它何时有焦点,何时失去了这个焦点。 我已经映射了大多数事件,如焦点监听器,OnEditorActionListener等,现在我唯一的问题是,当我有焦点时,软键盘会出现,我想关闭它: 1)通过完成按钮而不是通过电话上的后退按钮(在键盘可见时禁用后退按钮关闭键盘) 2)在键盘可见时检测后退按钮事件,以便我可以将焦点传递给其他控件。
我尝试了多种方法,但没有成功,例如onBackPressed,onConfigurationChanged(在清单中添加hiddenKeyboard),key_down on activity等等,但没有成功。
有人成功吗?实际上我想当键盘可见时我按回电话,我的编辑文字失去焦点(otherControl.requestFocus - >这是一个相对布局)。
答案 0 :(得分:10)
旧主题,但这是预期答案
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(getContext(), "BACK", Toast.LENGTH_SHORT).show();
return true;
}
return super.onKeyPreIme(keyCode, event);
}
你应该把它放在一个覆盖EditText的类中(类MyEditText扩展EditText ...)
答案 1 :(得分:4)
以下是捕获按键事件的方法: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;
}
}
2。 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"/>
3。然后从任何地方附加一个监听器:
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
}
}});
答案 2 :(得分:2)
这里是
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
{ //do you back event work here
}
return super.dispatchKeyEvent(event);
}