使用自定义布局时AutoCompleteTextView项无法点击的问题
解决AutoCompleteTextView自定义布局后项点击无响应的问题
这个问题我之前开发时也踩过坑!核心原因是你自定义项布局里的Button控件抢占了焦点,导致整个列表项的点击事件被拦截了。咱们一步步来解决:
一、修改自定义布局的焦点属性
在自定义项布局中,需要调整两个关键属性:
- 给根布局添加
android:descendantFocusability="blocksDescendants",让父布局优先获取焦点,阻止子控件抢占; - 给
Button添加android:focusable="false"和android:focusableInTouchMode="false",确保它不会干扰列表项的点击(但Button自身的onClick事件依然能正常触发)。
修改后的布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="viewModel" type="blog.liderc.familybudget.vms.DepartmentVM"/> <variable name="parentViewModel" type="blog.liderc.familybudget.AddSubjectViewModel"/> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:descendantFocusability="blocksDescendants"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="start" android:text="@{viewModel.title}" android:textSize="20sp"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="end" android:text="x" android:textSize="20sp" android:onClick="@{() -> parentViewModel.deleteDepartmentAsync(viewModel)}" android:focusable="false" android:focusableInTouchMode="false"/> </LinearLayout> </layout>
二、(可选)确保AutoCompleteTextView绑定了点击逻辑
如果调整焦点后还需要处理选中项的填充逻辑,可以给AutoCompleteTextView设置OnItemClickListener,示例代码如下:
view.department.setOnItemClickListener { parent, view, position, id -> val selectedDept = departments[position] // 将选中项的标题填充到输入框 view.department.setText(selectedDept.title) }
这样调整后,列表项的点击就能正常触发,同时Button的删除操作也不会受到影响~
内容的提问来源于stack exchange,提问作者Dmitry Matveyev
相关产品推荐
相关产品推荐

