点击屏幕隐藏软键盘、软键盘显示/隐藏、windowSoftInputMode常用属性说明(禁止软键盘自动弹出、键盘遮挡问题)

转载请注明出处:点击屏幕隐藏软键盘、软键盘显示/隐藏、windowSoftInputMode常用属性说明(禁止软键盘自动弹出、键盘遮挡问题)_当软键盘显示时更多面板应该隐藏_Mr_Leixiansheng的博客-CSDN博客

点击屏幕隐藏软键盘

1,实现方法一:通过给当前界面布局文件的父layout设置点击事件(相当于给整个Activity设置点击事件),在事件里进行键盘隐藏

  
  
  



加上id和clickable=true

然后在onCreate里,添加onClick事件的监听:

findViewById(R.id.traceroute_rootview).setOnClickListener(this);  
findViewById(R.id.traceroute_rootview).setOnClickListener(this);

在onClick中:

@Override  
public void onClick(View v) {  
    switch (v.getId()) {  
    case R.id.traceroute_rootview:  
         InputMethodManager imm = (InputMethodManager)  
         getSystemService(Context.INPUT_METHOD_SERVICE);  
         imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
        break;  
    }  
} 

这样就可以完美的解决了输入框外的隐藏效果,对于布局不是特别复杂或是其它触摸事件少的情况下可以使用。

2,实现思路二:通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件,然后在事件中进行屏蔽。

@Override  
public boolean dispatchTouchEvent(MotionEvent ev) {  
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
        View v = getCurrentFocus();  
        if (isShouldHideInput(v, ev)) {  
  
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
            if (imm != null) {  
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
            }  
        }  
        return super.dispatchTouchEvent(ev);  
    }  
    // 必不可少,否则所有的组件都不会有TouchEvent了  
    if (getWindow().superDispatchTouchEvent(ev)) {  
        return true;  
    }  
    return onTouchEvent(ev);  
}  

isShoudHideInput(View v,MotionEvent e)方法:

public  boolean isShouldHideInput(View v, MotionEvent event) {  
    if (v != null && (v instanceof EditText)) {  
        int[] leftTop = { 0, 0 };  
        //获取输入框当前的location位置  
        v.getLocationInWindow(leftTop);  
        int left = leftTop[0];  
        int top = leftTop[1];  
        int bottom = top + v.getHeight();  
        int right = left + v.getWidth();  
        if (event.getX() > left && event.getX() < right  
                && event.getY() > top && event.getY() < bottom) {  
            // 点击的是输入框区域,保留点击EditText的事件  
            return false;  
        } else {  
            return true;  
        }  
    }  
    return false;  
}  
	public  boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null && (v instanceof EditText)) {
			int[] leftTop = { 0, 0 };
			//获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
			int top = leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if (event.getX() > left && event.getX() < right
					&& event.getY() > top && event.getY() < bottom) {
				// 点击的是输入框区域,保留点击EditText的事件
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

这种方法实现起来比较麻烦,解决思路与iOS中的事件分发机制是类似,对于处理隐藏事件比较清晰,通过层层事件分发,然后判断是否在需要屏蔽的区域。

软键盘显示/隐藏

public static void showSoftInput(Context context, View view){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		//imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
	}
	
	public static void hideSoftInput(Context context, View view){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
	}
	
	public static boolean isShowSoftInput(Context context){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		//获取状态信息
		return imm.isActive();//true 打开
	}

windowSoftInputMode(AndroidManifest.xml)常用属性说明

有时候在布局包含EditText时,进入页面就会自动弹出软键盘,有时这种用户体验并不好,所以我们要手动去控制

1、"stateUnspecified"
软键盘的状态 (是否它是隐藏或可见 )没有被指定。系统将选择一个合适的状态或依赖于主题的设置。
这个是为了软件盘行为默认的设置。

2、"stateUnchanged"
软键盘被保持无论它上次是什么状态,是否可见或隐藏,当主窗口出现在前面时。

3、"stateHidden"
当用户选择该 Activity时,软键盘被隐藏——也就是,当用户确定导航到该 Activity时,而不是返回到它由于离开另一个 Activity。

4、"stateAlwaysHidden"
软键盘总是被隐藏的,当该 Activity主窗口获取焦点时。

5、"stateVisible"
软键盘是可见的,当那个是正常合适的时 (当用户导航到 Activity主窗口时 )。

6、"stateAlwaysVisible"
当用户选择这个 Activity时,软键盘是可见的——也就是,也就是,当用户确定导航到该 Activity时,而不是返回到它由于离开另一个 Activity。

7、"adjustUnspecified"
它不被指定是否该 Activity主 窗口调整大小以便留出软键盘的空间,或是否窗口上的内容得到屏幕上当前的焦点是可见的。系统将自动选择这些模式中一种主要依赖于是否窗口的内容有任何布局 视图能够滚动他们的内容。如果有这样的一个视图,这个窗口将调整大小,这样的假设可以使滚动窗口的内容在一个较小的区域中可见的。这个是主窗口默认的行为 设置。

8、"adjustResize"
该 Activity主窗口总是被调整屏幕的大小以便留出软键盘的空间

9、"adjustPan"
该 Activity主窗口并不调整屏幕的大小以便留出软键盘的空间。相反,当前窗口的内容将自动移动以便当前焦点从不被键盘覆盖和用户能总是看到输入内容的部分。这个通常是不期望比调整大小,因为用户可能关闭软键盘以便获得与被覆盖内容的交互操作。

 全屏模式下软键盘遮挡问题

非全屏模式下设置adjustResize即可解决遮挡

 android:windowSoftInputMode="adjustResize"

全屏模式下只设置adjustResize会发现无效

还需要加入以下工具重新计算高度

 class SoftHideKeyBoardUtil {

    public static void assistActivity (Activity activity) {
        new SoftHideKeyBoardUtil(activity);
    }
    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;
    //为适应华为小米等手机键盘上方出现黑条或不适配
    private int contentHeight;//获取setContentView本来view的高度
    private boolean isfirst = true;//只用获取一次
    private  int statusBarHeight;//状态栏高度
    private SoftHideKeyBoardUtil(Activity activity) {
        //1、找到Activity的最外层布局控件,它其实是一个DecorView,它所用的控件就是FrameLayout
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        //2、获取到setContentView放进去的View
        mChildOfContent = content.getChildAt(0);
        //3、给Activity的xml布局设置View树监听,当布局有变化,如键盘弹出或收起时,都会回调此监听
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            //4、软键盘弹起会使GlobalLayout发生变化
            public void onGlobalLayout() {
                if (isfirst) {
                    contentHeight = mChildOfContent.getHeight();//兼容华为等机型
                    isfirst = false;
                }
                //5、当前布局发生变化时,对Activity的xml布局进行重绘
                possiblyResizeChildOfContent();
            }
        });
        //6、获取到Activity的xml布局的放置参数
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
        statusBarHeight = getStatusBarHeight(activity);
    }

    // 获取界面可用高度,如果软键盘弹起后,Activity的xml布局可用高度需要减去键盘高度
    private void possiblyResizeChildOfContent() {
        //1、获取当前界面可用高度,键盘弹起后,当前界面可用布局会减少键盘的高度
        int usableHeightNow = computeUsableHeight();
        //2、如果当前可用高度和原始值不一样
        if (usableHeightNow != usableHeightPrevious) {
            //3、获取Activity中xml中布局在当前界面显示的高度
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            //4、Activity中xml布局的高度-当前可用高度
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            //5、高度差大于屏幕1/4时,说明键盘弹出
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // 6、键盘弹出了,Activity的xml布局高度应当减去键盘高度
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference + statusBarHeight;
                } else {
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
                }
            } else {
                frameLayoutParams.height = contentHeight;
            }
            //7、 重绘Activity的xml布局
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }
    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        // 全屏模式下:直接返回r.bottom,r.top其实是状态栏的高度
        return (r.bottom - r.top);
    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

}

在setContentView(R.layout.xxx)后调用SoftHideKeyBoardUtil.assistActivity(context);

你可能感兴趣的:(android,ui)