很多时候,我们在使用应用时,会出现输入法软键盘弹出的问题,通常情况下,我们默认会使用户点击返回键或者下一步对软键盘进行隐藏。为了更好的体验,我们可以实现当用户使用完毕软键盘时。点击空白区域即可实现隐藏的功能。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View view = getWindow().getDecorView();
if(isShouldHideSoftInput(view,ev.getX(),ev.getY())){
hideSoftInput();
}
}
return super.dispatchTouchEvent(ev);
}
public void hideSoftInput() {
View view = this.getCurrentFocus();
if(view!=null){
IBinder ib = view.getWindowToken();
if(ib!=null){
InputMethodManager im = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
if(im.isActive()){
im.hideSoftInputFromWindow(ib, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}
public boolean isShouldHideSoftInput(View view,float x,float y){
boolean shouldHide = true;
if(isDownView(view,x,y)){
if(view instanceof ViewGroup){
ViewGroup viewGroup = (ViewGroup)view;
for(int i = 0;i<viewGroup.getChildCount();i++){
shouldHide = isShouldHideSoftInput(viewGroup.getChildAt(i),x,y);
if(!shouldHide){
break;
}
}
}else{
if(view instanceof EditText||view instanceof AppCompatEditText){
shouldHide = false;
}
}
}
return shouldHide;
}
public boolean isDownView(View view,float x,float y){
boolean thisView = false;
int[] location = new int[2];
view.getLocationOnScreen(location);
int xl = location[0];
int yl = location[1];
if(x>xl&&x<xl+view.getWidth()&&y>yl&&y<yl+view.getHeight()){
thisView = true;
}
return thisView;
}