Tap outside edittext to lose focus(点击外部edittext失去焦点)
问题描述
我只想在edittext"外部单击时自动失去焦点并隐藏键盘.目前,如果我点击edittext"它会聚焦,但我需要点击后退按钮才能取消聚焦.
I just want when click outside the "edittext" to automatically lose focus and hide keyboard. At the moment, if I click on the "edittext" it focuses but i need to hit the back button to unfocus.
推荐答案
要解决这个问题,首先要使用 Edittext 的 setOnFocusChangeListener
To solve this problem what you have to do is first use setOnFocusChangeListener of that Edittext
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.d("focus", "focus lost");
// Do whatever you want here
} else {
Log.d("focus", "focused");
}
}
});
然后您需要做的是在包含 Edittext 的活动中覆盖 dispatchTouchEvent,请参见下面的代码
and then what you need to do is override dispatchTouchEvent in the activity which contains that Edittext see below code
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
Log.d("focus", "touchevent");
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(event);
}
现在会发生什么,当用户点击外部时,首先会调用这个 dispatchTouchEvent,然后从 editext 清除焦点,现在你的 OnFocusChangeListener 将被调用,焦点已经改变,现在你可以做任何你想做的事情想做,希望有效:)
Now what will happen is when a user click outside then, firstly this dispatchTouchEvent will get called which then will clear focus from the editext, now your OnFocusChangeListener will get called that focus has been changed, now here you can do anything which you wanted to do, hope it works :)
这篇关于点击外部edittext失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:点击外部edittext失去焦点


- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- android 4中的android RadioButton问题 2022-01-01