我有一个包含RecyclerView
个子元素的EditText
。我想在屏幕上滚动选定的EditText
时隐藏软键盘。如何判断EditText
何时不在屏幕上?是否有一些事件监听器可以附加到EditText
元素来告诉?
答案 0 :(得分:19)
像这样实施onTouchListener
:
yourRecycleView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return false;
}
});
答案 1 :(得分:0)
yourRecycleView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edittext.clearFocus(); //hidden keyboard
return false;
}
});
答案 2 :(得分:0)
我的解决方案:
editText.setOnFocusChangeListener((v, hasFocus) -> {
Handler handler = new Handler();
if (!hasFocus) {
handler.postDelayed(() -> {
if (!editText.hasFocus()) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, 0);
}
}, 200);
}
});
答案 3 :(得分:0)
这对我有用:我使用RecyclerView.OnScrollListener
和PublishRelay
来消除事件。
class RecyclerViewActivity : Activity(){
...
private val scrollableRelay = PublishRelay.create<Unit>()
private val disposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
scrollableRelay.accept(Unit)
}
})
scrollableRelay
.debounce(100, TimeUnit.MILLISECONDS)
.subscribe({
if (currentFocus == recyclerView) {
hideKeyboard()
}
})
.addTo(disposable)
}
override fun onDestroy() {
disposable.onDestroy()
}
}
一旦视图从屏幕上滚动,焦点就会上升到recyclerView。
因此,我们可以使用RecyclerView.OnScrollListener
来实现此功能。
onScrolled
甚至跟踪视图的最细微滚动。这就是为什么我们需要添加debounce
来避免收到很多事件的原因。
hideKeyboard
和addTo
是扩展功能:
fun Disposable.addTo(compositeDisposable: CompositeDisposable) {
compositeDisposable.add(this)
}
fun Activity.hideKeyboard() =
currentFocus?.let {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
答案 4 :(得分:0)
在以下情况下解散键盘的Kotlin解决方案:
View
从RecyclerView
滚动下来RecyclerView
... // dismiss the keyboard when it is no longer focusing on anything inside the recyclerview
recyclerView.viewTreeObserver.addOnGlobalFocusChangeListener { _, newFocus: View? ->
if (newFocus == recyclerView || recyclerView !in (newFocus?.ancestors ?: emptySequence())) {
recyclerView.context.inputService.hideSoftInputFromWindow(recyclerView.windowToken, 0)
}
}
val Context.inputService get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val View.ancestors: Sequence<View> get() = generateSequence(this) { it.parent as? View }