从软键盘拦截后退按钮

时间:2010-10-15 06:59:31

标签: android

我有几个输入字段的活动。当活动开始时,显示软键盘。当按下后退按钮软键盘关闭并关闭活动时,我需要再次按下后退按钮。

所以问题是:是否可以拦截后退按钮关闭软键盘,只需按一下后退按钮即可完成活动,而无需创建自定义InputMethodService

P.S。我知道在其他情况下如何拦截后退按钮:onKeyDown()onBackPressed()但在这种情况下它不起作用:只有第二次按下后退按钮才被拦截。

10 个答案:

答案 0 :(得分:73)

是的,完全可以显示和隐藏键盘并拦截对后退按钮的调用。这是一个额外的努力,因为已经提到在API中没有直接的方法来做到这一点。关键是覆盖布局中的boolean dispatchKeyEventPreIme(KeyEvent)。我们做的是创建我们的布局。我选择了RelativeLayout,因为它是我活动的基础。

<?xml version="1.0" encoding="utf-8"?>
<com.michaelhradek.superapp.utilities.SearchLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.michaelhradek.superapp"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white">

在我们的Activity中,我们设置输入字段并调用setActivity(...)函数。

private void initInputField() {
    mInputField = (EditText) findViewById(R.id.searchInput);        

    InputMethodManager imm = 
        (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 
            InputMethodManager.HIDE_IMPLICIT_ONLY);

    mInputField.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }

            return false;
        }
    });

    // Let the layout know we are going to be overriding the back button
    SearchLayout.setSearchActivity(this);
}

显然,initInputField()函数设置输入字段。它还使enter键能够执行功能(在我的例子中是搜索)。

@Override
public void onBackPressed() {
    // It's expensive, if running turn it off.
    DataHelper.cancelSearch();
    hideKeyboard();
    super.onBackPressed();
}

因此,当我们在布局中调用onBackPressed()时,我们可以做任何我们想做的事情,比如隐藏键盘:

private void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) 
        getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(mInputField.getWindowToken(), 0);
}

无论如何,这是我对RelativeLayout的重写。

package com.michaelhradek.superapp.utilities;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RelativeLayout;

/**
 * The root element in the search bar layout. This is a custom view just to 
 * override the handling of the back button.
 * 
 */
public class SearchLayout extends RelativeLayout {

    private static final String TAG = "SearchLayout";

    private static Activity mSearchActivity;;

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

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

    public static void setSearchActivity(Activity searchActivity) {
        mSearchActivity = searchActivity;
    }

    /**
     * Overrides the handling of the back key to move back to the 
     * previous sources or dismiss the search dialog, instead of 
     * dismissing the input method.
     */
    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        Log.d(TAG, "dispatchKeyEventPreIme(" + event + ")");
        if (mSearchActivity != null && 
                    event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            KeyEvent.DispatcherState state = getKeyDispatcherState();
            if (state != null) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getRepeatCount() == 0) {
                    state.startTracking(event, this);
                    return true;
                } else if (event.getAction() == KeyEvent.ACTION_UP
                        && !event.isCanceled() && state.isTracking(event)) {
                    mSearchActivity.onBackPressed();
                    return true;
                }
            }
        }

        return super.dispatchKeyEventPreIme(event);
    }
}

不幸的是,我无法承担所有的功劳。如果您查看Android source for the quick SearchDialog box,您会看到该想法的来源。

答案 1 :(得分:66)

onKeyDown() onBackPressed()对于这种情况不起作用。您必须使用 onKeyPreIme

最初,您必须创建扩展EditText的自定义编辑文本。然后你必须实现控制 KeyEvent.KEYCODE_BACK 的onKeyPreIme方法。在此之后,一个足以解决您的问题。这个解决方案非常适合我。

<强> CustomEditText.java

public class CustomEditText extends EditText {

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

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // User has pressed Back key. So hide the keyboard
            InputMethodManager mgr = (InputMethodManager)         

           getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
            // TODO: Hide your view as you do it in your activity
        }
        return false;
}

在您的XML中

<com.YOURAPP.CustomEditText
     android:id="@+id/CEditText"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"/> 

在您的活动中

public class MainActivity extends Activity {
   private CustomEditText editText;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      editText = (CustomEditText) findViewById(R.id.CEditText);
   }
}

答案 2 :(得分:9)

我发现,覆盖布局类的 dispatchKeyEventPreIme 方法也很有效。只需将主Activity设置为属性并启动预定义方法。

public class LinearLayoutGradient extends LinearLayout {
    MainActivity a;

    public void setMainActivity(MainActivity a) {
        this.a = a;
    }

    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (a != null) {
            InputMethodManager imm = (InputMethodManager) a
                .getSystemService(Context.INPUT_METHOD_SERVICE);

            if (imm.isActive() && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                a.launchMethod;
            }
        }

        return super.dispatchKeyEventPreIme(event);
    }
}

答案 3 :(得分:7)

我通过覆盖 dispatchKeyEvent

取得了成功
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        finish();
        return true;
    }
    return super.dispatchKeyEvent(event);
}

隐藏键盘并完成活动。

答案 4 :(得分:4)

你是如何展示软键盘的?

如果您使用的是InputMethodManager.showSoftInput(),则可以尝试传递ResultReceiver并实施onReceiveResult()来处理RESULT_HIDDEN

http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html

答案 5 :(得分:2)

我遇到了同样的问题,但通过拦截后退按键来绕过它。在我的情况下(HTC Desire,Android 2.2,Application API Level 4),它关闭键盘并立即完成活动。不知道为什么这对你也不适用:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

/**
 * Called when the activity has detected the user's press of the back key
 */
private void onBackPressed() {
    Log.e(TAG, "back pressed");
    finish();
}

答案 6 :(得分:1)

使用onKeyPreIme(int keyCode, KeyEvent event)方法检查KeyEvent.KEYCODE_BACK事件。没有做任何花哨的编码就很简单。

答案 7 :(得分:0)

在BackPressed实施中尝试此代码(Block Back Button in android):

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

我建议你看看@ Close/hide the Android Soft Keyboard

答案 8 :(得分:0)

我的@mhradek解决方案版本:

布局

class BazingaLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    ConstraintLayout(context, attrs, defStyleAttr) {

var activity: Activity? = null

override fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
    activity?.let {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            val state = keyDispatcherState
            if (state != null) {
                if (event.action == KeyEvent.ACTION_DOWN
                    && event.repeatCount == 0) {
                    state.startTracking(event, this)
                    return true
                } else if (event.action == KeyEvent.ACTION_UP && !event.isCanceled && state.isTracking(event)) {
                    it.onBackPressed()
                    return true
                }
            }
        }
    }
    return super.dispatchKeyEventPreIme(event)
}

}

xml文件

<com... BazingaLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/grey">
 </com... BazingaLayout>

片段

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        (view as BazingaLayout).activity = activity
        super.onViewCreated(view, savedInstanceState)
}

答案 9 :(得分:0)

这是我对 @kirill-rakhman's 解决方案的变体。

我需要知道在键盘显示时按下硬件或手势返回按钮的时间,以便我可以做出反应并显示以前在任何编辑文本视图获得焦点时隐藏的按钮。

  1. 首先声明你需要的回调接口
interface KeyboardEventListener {
   fun onKeyBoardDismissedIme()
}
  1. 然后使用侦听器为 pre ime 键事件创建自定义视图
class KeyboardAwareConstraintLayout(context: Context, attrs: AttributeSet) :
    ConstraintLayout(context, attrs) {

    var listener: KeyboardEventListener? = null

    override fun dispatchKeyEventPreIme(event: KeyEvent?): Boolean {
        val imm: InputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive && event?.keyCode == KeyEvent.KEYCODE_BACK) {
            listener?.onKeyBoardDismissedIme()
        }
        return super.dispatchKeyEventPreIme(event)
    }
}
  1. 使用自定义布局视图包装您的布局
<com.package_name.KeyboardAwareLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/keyBoardAwareLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

{Your layout children here}    

</com.package_name.KeyboardAwareLayout>

  1. 接下来在您的活动或片段中实现回调接口并设置键盘感知布局
class MyFragment : Fragment, KeyboardEventListener {

    // TODO: Setup some viewbinding to retrieve the view reference

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.keyBoardAwareLayout.listener = this
    }

    override fun onKeyBoardDismissedIme() {
        // TODO: React to keyboard hidden with back button
    }
}