繁体   English   中英

隐藏Android虚拟键盘

[英]Hide Android Virtual Keyboard

我有一个显示EditText和两个底部的活动。

当我点击EditText时,Android虚拟键盘会显示出来,这样我就可以输入我的文字了。 现在,在任何底部敲击之前我想隐藏键盘。 我想通过点击屏幕来实现。

我在stackoverflow中看到过一些类似问题的帖子,但看起来不像工作。 我试图设置一个监听器:

   // Create an anonymous implementation of OnFocusChangeListener
   private OnFocusChangeListener mFocusListener = new OnFocusChangeListener() {
       public void onFocusChange(View v, boolean b) {
          // do something when the focus changes
        hideSoftKeyboard(v);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setupUI(findViewById(R.id.parent));
        EditText editText = (EditText) findViewById (R.id.edit_message);
        editText.setOnFocusChangeListener(mFocusListener);
        setContentView(R.layout.activity_main);
    }

我还尝试创建一个父活动,递归地将onTouch事件关联到每个不是文本视图的视图,但它只注册文本视图(我从另一个stackoverflow帖子中获取了这段代码)

    public void setupUI(View view) {

    //Set up touch listener for non-text box views to hide keyboard.
    if(!(view instanceof EditText)) {

        view.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(v);
                return false;
            }

        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {

        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

            View innerView = ((ViewGroup) view).getChildAt(i);

            setupUI(innerView);
        }
    }
}

对此有任何坚定的前瞻性解决方案? 我无法相信没有更简单的方法来做到这一点。 我正在使用Gingerbread API(API级别10)

谢谢

好的,我找到了一种以非常简单的方式完成此任务的方法:XML布局定义。 由于Layout是ViewGroup,我们可以在其上实现事件。 去定义处理布局点击的方法(hideSoftKeyboard)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" 
    android:id="@+id/main_layout" 
    android:onClick="hideSoftKeyboard" >

以下是我实现该方法的方法:

public void hideSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager)  getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

我出于同样的目的使用了以下方法

private void hideKeypad(){
    EditText edtView=(EditText)findViewById(R.id.username);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM