Material AutoCompleteTextView下拉菜单在DialogFragment中无法正常工作

问题描述
- 尝试使用Material组件提供的AutoCompleteTextView实现下拉选择菜单,完成代码编写后查阅资料校验,确认逻辑本该正常生效,但实际功能无法运行。
- DialogFragment是和其他Fragment共同渲染在页面上的,暂时不确定这是否是问题产生的诱因。
- 目前初步推测是Adapter配置存在问题,希望获得对应的排障思路与方向提示。
- 此前尝试发布XML布局代码时,即便使用缩进工具做了格式处理,StackOverflow仍无法正常解析代码块,因此本次提问没有附上XML代码。
附带代码
DialogFragment 中的代码
import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import android.view.MenuInflater import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView class AddBillFragment: DialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { var rootView = inflater.inflate(R.layout.fragment_add_bill,container,false) var autoCompleteTextView: AutoCompleteTextView? = view?.findViewById(R.id.autoComplete) val options: Array<String> = arrayOf("option1", "option2") val arrayAdapter = getActivity()?.let { ArrayAdapter<String>( it.getApplicationContext(), R.layout.add_bill_type_items, options ) } autoCompleteTextView?.setAdapter(arrayAdapter) return rootView } }
注:以上代码仅做换行排版方便阅读,核心逻辑与原贴内容完全一致
排障方向
从代码逻辑来看,有几处会直接导致功能失效的问题,可以优先修正:
- 视图引用错误:
onCreateView执行阶段,Fragment的全局view属性还未完成赋值,此时用view?.findViewById(R.id.autoComplete)获取到的控件为null,后续的Adapter绑定操作完全不会执行。需要替换为已经inflate完成的rootView来查找控件实例。 - 上下文选择错误:初始化ArrayAdapter时传入了ApplicationContext,AutoCompleteTextView的下拉弹窗需要依附当前页面的窗口令牌才能正常展示,使用全局应用上下文会导致弹窗无权限弹出。应当替换为当前Fragment所属Activity的上下文,不要使用ApplicationContext。
- 触发阈值不匹配:AutoCompleteTextView默认需要输入至少1个字符才会唤起下拉列表,如果希望点击控件就直接展示全部选项,需要手动调用
autoCompleteTextView.setThreshold(0)调整触发阈值。 - 多Fragment共同渲染的布局结构,不会直接影响AutoCompleteTextView的功能,不属于问题产生的核心诱因。
内容的提问来源于stack exchange,提问作者yazmnh87
相关产品推荐
相关产品推荐

