1,實現方法一:通過給當前界面布局文件的父layout設置點擊事件(相當于給整個Activity設置點擊事件),在事件里進行鍵盤隱藏
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/traceroute_rootview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:clickable="true"
android:gravity="center_horizontal"
android:orientation="vertical" >
</LinearLayout>
加上id和clickable=true
然后在onCreate里,添加onClick事件的監聽:
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;
}
這種方法實現起來比較麻煩,解決思路與iOS中的事件分發機制是類似,對于處理隱藏事件比較清晰,通過層層事件分發,然后判斷是否在需要屏蔽的區域。