android 点击editview以外位置实现隐藏输入法
实现代码:
@override
public boolean dispatchtouchevent(motionevent ev) {
if (ev.getaction() == motionevent.action_down) {
view v = getactivity().getcurrentfocus();
if (isshouldhideinput(v, ev)) {
inputmethodmanager imm = (inputmethodmanager) getactivity().getsystemservice(context.input_method_service);
if (imm != null) {
imm.hidesoftinputfromwindow(v.getwindowtoken(), 0);
}
}
return getactivity().dispatchtouchevent(ev);
}
// 必不可少,否则所有的组件都不会有touchevent了
if (getactivity().getwindow().superdispatchtouchevent(ev)) {
return true;
}
return getactivity().ontouchevent(ev);
}
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;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!