首页 > 移动平台 > 详细

Android基础-EditText之隐藏键盘

时间:2015-12-01 10:58:20      阅读:459      评论:0      收藏:0      [点我收藏+]

场景一、点击EditText之外的空白区域隐藏键盘:

how to hide soft keyboard on android after clicking outside EditText?

首先定义一个关闭键盘的方法:

    /**
     * 关闭软键盘
     */
    public static void closeSoftKeyboard(Context context) {
        InputMethodManager inputMethodManager = (InputMethodManager)context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && ((Activity)context).getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(((Activity)context).getCurrentFocus()
                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

如果用户选择或者点击了输入框以外的区域怎么隐藏掉已经弹出的键盘呢?需要遍历Activity中每个View并检查它是否是EditText的实例,如果不是就注册一个setOnTouchListener,只要点击了该View就会触发它的OnTouch方法,从而在里面隐藏键盘。但实际有更简单的方法可以处理View和ViewGroup,那就是利用下面的递归方法,这个方法其实用处很多,还可以同来设置自定义字体。

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(MyActivity.this);
                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);
        }
    }
}

这样在Activity的setContentViewi之后就能调用上面的setupUI方法了,其中的参数View是Activity的布局的rootView。为Activity的根布局指定一个id就可以了 。

如果想有效的使用该方法,可以把上面的方法放到BaseActivity中,继承它的Activity在onCreate()中调用setupUI就可以了。

场景二、进入带有EditText的Activity时隐藏键盘

这时候一般EditText会获取自动获取焦点然后弹出键盘。进入页面时不自动弹出的话可以:

在EditText的外层layout上设置:

android:focusable="true"

android:focusableInTouchMode="true"

或者强制隐藏Android输入法窗口
例如:  EditText edit=(EditText)findViewById(R.id.edit);  
           InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
           imm.hideSoftInputFromWindow(edit.getWindowToken(),0);

注意:在AndroidMainfest.xml中设置使用EditText的activity的属性,设置windowSoftInputMode属性为adjustUnspecified|stateHidden

 

Android基础-EditText之隐藏键盘

原文:http://www.cnblogs.com/permanent2012moira/p/5009421.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!