我来自iOS开发,并且是Android应用程序开发的新手,在Android中对我来说确实有些奇怪,为什么隐藏键盘时EditText会保持焦点?
我试图在EditText上设置OnFocusChangeListener,但是当键盘隐藏,未调用侦听器时,此方法不起作用。
我还尝试使用onChangeListener检测键盘隐藏,但是它不起作用..(显然仅适用于硬键盘)。
@Override
public void onFocusChange(View v, boolean hasFocus) {
// not called when keyboard hides
}
});
我已经寻找了一段时间,但我只找到了在首次启动时停止关注的答案,但这不是我想要的。
谢谢
答案 0 :(得分:1)
好吧,这样
private void setUpEtxFocusListener() {
etx.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
if ((LOG_DEBUG)) Log.d(TAG, "etx : GOT Focus");
} else {
if ((LOG_DEBUG)) Log.d(TAG, "etx : LOST Focus");
}
}
});
在外部单击时,etx将失去焦点,并且您隐藏了键盘
//this will trigger etx setOnFocusChangeListener - onFocus change() - NO FOCUS clause
@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())) {
v.clearFocus();
// just an utility class to hide.
UtilExtra.hideKeyboard(this);
}
}
}
return super.dispatchTouchEvent(event);
}
答案 1 :(得分:0)
尝试一下:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
答案 2 :(得分:0)
您只需使用此代码,您的焦点就会消失
editText.clearFocus();
答案 3 :(得分:0)
要捕获键盘的打开/关闭事件,请使用以下代码:
//...
private int layoutSize = 0;
private boolean isKeyboardVisible = false;
//...
@Override
public void onCreate(Bundle savedInstanceState) {
setKeyboardOpenListener();
}
//...
private void setKeyboardOpenListener() {
View activityRootView = findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
if (activityRootView.getHeight() + Util.getStatusBarHeight(this) >= layoutSize) {
layoutSize = activityRootView.getHeight();
if (isKeyboardVisible) {
isKeyboardVisible = false;
onKeyboardClose();
}
} else {
if (!isKeyboardVisible) {
isKeyboardVisible = true;
onKeyboardOpen();
}
}
});
}
//...
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
答案 4 :(得分:0)
最近,我通过一个好的库解决了这个问题。它处理Keyboard visibility event.
将此添加到您的应用级Gradle文件。
dependencies {
implementation'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:2.3.0'
}
启用键盘事件:
KeyboardVisibilityEvent.setEventListener(
getActivity(),
new KeyboardVisibilityEventListener() {
@Override
public void onVisibilityChanged(boolean isOpen) {
if (isOpen)
//Keyboard is showing.
else
yourEditText.clearFocus()
yourEditText.setCursorVisible(false) //Only if the cursor keeps blinking else no need use it.
//Keyboard is now closed.
}
});
遗憾的是,没有“适当”的方式来处理键盘可见性事件。您所得到的只是用于检测它的黑客。
答案 5 :(得分:-1)
同时使用editText.clearFocus()和editText.setCursorVisible(false)这两种方法,可能会对您有所帮助。