目标:点击EditText之外的区域,收起键盘,并且让EditText失去焦点。
贴代码一:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}"
android:focusable="true"
android:focusableInTouchMode="true" >
<!-- 这里有两种办法:
第一种是RelativeLayout中加入focusable,focusableInTouchMode两种属性
第二种是 新建一个View如下,可获取焦点
<View
android:layout_width="0dip"
android:layout_height="0dip"
android:focusable="true"
android:focusableInTouchMode="true" /> -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="input something"
android:id="@+id/editText"
android:layout_alignParentBottom="true"
android:focusableInTouchMode="true"/>
</RelativeLayout>
之前一直不成功的原因在于,我写的xml代码中,EditText是唯一可foucs的View,所以将其clearFocus()之后,焦点仍在EditText中,好像clearFocus()不起作用。 参考博客: http://blog.csdn.net/yzx41099296/article/details/9145647
贴代码二:
public class MainActivity extends Activity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
editText=(EditText)findViewById(R.id.editText);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(ev.getAction()==MotionEvent.ACTION_DOWN){
View v=getCurrentFocus();
boolean hideInputResult =isShouldHideInput(v,ev);
Log.v("hideInputResult","zzz-->>"+hideInputResult);
if(hideInputResult){
v.clearFocus();
InputMethodManager imm = (InputMethodManager) MainActivity.this
.getSystemService(Activity.INPUT_METHOD_SERVICE);
if(v != null){
if(imm.isActive()){
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}
return super.dispatchTouchEvent(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();
//之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标!!!
Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
if (event.getRawX() > left && event.getRawX() < right
&& event.getRawY() > top && event.getRawY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
}
贴截图: