[英]Android OnClickListener only triggered on second click
我的 OnClickListener 只会在第二次点击时被调用。 同一 View 的 OnLongClickListener 按预期工作。 我尝试使用 OnTouchListener 代替,但在滑动时显然会触发。
我的侦听器是我在活动中实现的接口的抽象方法:
interface OnVocableFlashcardFragmentInteractionListener {
fun onEditTextLongClick(view: View): Boolean
fun onEditTextClick(view: View)
}
我在我的 RecyclerViewAdapter 类中像这样设置我的视图的侦听器:
init{
setHasStableIds(true)
mEditTextOnClickListener = View.OnClickListener {
mListener.onEditTextClick(it)
}
mEditTextOnLongClickListener = View.OnLongClickListener {
mListener.onEditTextLongClick(it)
}
}
override fun onBindViewHolder(holder: FlashcardViewHolder, position: Int) {
...
editText.let { it.tag = it.keyListener; it.keyListener = null; }
editText.setOnClickListener(mEditTextOnClickListener)
editText.setOnLongClickListener(mEditTextOnLongClickListener)
...
}
我的活动中侦听器的实现如下所示:
override fun onEditTextClick(view: View) {
//-- only show toast if view is not editable (becomes editable on LongClick)
if ((view as EditText).keyListener == null) {
if (mToast != null) {
mToast!!.cancel()
}
//-- inform user to long press to edit entry
mToast = Toast.makeText(this, resources.getString(R.string.long_click_to_edit), Toast.LENGTH_LONG)
mToast!!.show()
}
}
override fun onEditTextLongClick(view: View): Boolean {
//-- I saved the KeyListener in the editTexts tag attribute
//-- to make it clickable again when needed
(view as EditText).keyListener = view.getTag() as KeyListener
showSoftKeyboard(view)
return true
}
我的视图的 XML 如下所示:
<EditText
android:id="@+id/et_vocable_word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@null"
android:textStyle="bold"
android:hint="@string/enter_word"
android:imeOptions="actionNext"
android:inputType="textNoSuggestions"
android:maxLines="1"
android:singleLine="true" />
视图的父级及其父级未声明为android:focusable="true"
或android:clickable="true"
在我的 AndroidManifest.xml 中,我为我的活动设置了android:windowSoftInputMode="stateHidden"
以防止 SoftInput 在活动开始时出现。
我做错了什么,或者为什么 OnClickListener 只在第二次点击时被调用? 有没有人有我如何解决问题的想法?
您必须将编辑文本可聚焦属性设为 false,因为其默认值为 auto,这意味着框架确定它必须为 true 和 false。当您第一次触摸时为 true 时,它已被键盘聚焦。
https://developer.android.com/reference/android/R.styleable#View_focusable
我能够通过使用 OnTouchListener 而不是 OnClickListener 来实现所需的行为,如下所示:
override fun onEditTextTouch(editText: EditText, event: MotionEvent): Boolean {
//-- if the pressed gesture has finished
if (event.action == MotionEvent.ACTION_UP)
//-- only show toast if view is not editable (becomes editable on LongClick)
if (editText.keyListener == null) {
if (mToast != null) {
mToast!!.cancel()
}
//-- inform user to long press to edit entry
mToast = Toast.makeText(this, resources.getString(R.string.long_click_to_edit), Toast.LENGTH_LONG)
mToast!!.show()
}
return false
}
在我之前尝试用 touchListener 替换我的 clickListener 时,我忘记检查(event.action == MotionEvent.ACTION_UP)
所以我的代码在滑动时也被执行(我不想要)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.