单击滑动菜单导航时片段中的隐藏键盘

时间:2014-06-03 09:37:51

标签: android android-fragments slidingmenu

我想在单击“菜单”时使用“滑动菜单”隐藏片段A中的edittext键盘。 我尝试使用:

      @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);

    if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    return true;
}

@Override
        public void onDrawerClosed(View drawerView) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(drawerView);
            getWindow()
                    .setSoftInputMode(
                            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            super.onDrawerOpened(drawerView);
            getWindow()
                    .setSoftInputMode(
                            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }

但都没有用。请帮我。谢谢!

2 个答案:

答案 0 :(得分:1)

Fragment

中尝试这种方式
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);

Activity

  InputMethodManager inputManager = (InputMethodManager) your_activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
View view = your_activity.this.getCurrentFocus();
if (view != null) {
    inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

另一种方法是尝试在dispatchTouchEvent(....)中实施Activity

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    View view = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (view instanceof EditText) {
        View w = getCurrentFocus();
        int scrcoords[] = new int[2];
        w.getLocationOnScreen(scrcoords);
        float x = event.getRawX() + w.getLeft() - scrcoords[0];
        float y = event.getRawY() + w.getTop() - scrcoords[1];

        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
        }
    }
    return ret;
}

答案 1 :(得分:1)

public static void hideKeyboardForFocusedView(Activity activity) {
    InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    View view = activity.getCurrentFocus();
    if (view != null) {
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

此方法隐藏任何EditText的键盘。

相关问题