如何为inputType为none的AutoCompleteTextView设置适配器默认值
如何设置AutoCompleteTextView初始选中ArrayAdapter指定项?
我的布局代码如下:
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="match_parent" style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"> <AutoCompleteTextView android:id="@+id/actv_choices" android:layout_width="match_parent" android:layout_height="match_parent" android:hint="Choose" android:inputType="none" android:text="Handicapped "/> </com.google.android.material.textfield.TextInputLayout>
当前布局直接给AutoCompleteTextView设置了固定文本,但我需要在Activity启动时,自动将其初始值设置为绑定的ArrayAdapter列表中的指定项(例如列表的第二项),让文本与适配器列表项关联,而非固定硬编码。
实现步骤:
初始化并绑定ArrayAdapter
首先在Activity的onCreate方法中,创建适配器并绑定到AutoCompleteTextView:Kotlin代码:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.your_layout) // 替换为你的实际选项列表 val choicesList = listOf("Normal", "Handicapped", "Elderly") val adapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, choicesList) val actvChoices = findViewById<AutoCompleteTextView>(R.id.actv_choices) actvChoices.setAdapter(adapter) }Java代码:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); // 替换为你的实际选项列表 List<String> choicesList = Arrays.asList("Normal", "Handicapped", "Elderly"); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, choicesList); AutoCompleteTextView actvChoices = findViewById(R.id.actv_choices); actvChoices.setAdapter(adapter); }设置指定项为初始值
在绑定适配器后,获取列表中的目标项,调用setText()方法设置初始值,注意第二个参数传false,避免触发下拉列表弹出:Kotlin代码:
// 选择列表的第二项(索引为1,列表从0开始计数) val defaultChoice = choicesList[1] actvChoices.setText(defaultChoice, false)Java代码:
// 选择列表的第二项(索引为1,列表从0开始计数) String defaultChoice = choicesList.get(1); actvChoices.setText(defaultChoice, false);
关键说明:
- 不要直接在布局中硬编码
android:text,因为这样的文本和适配器列表没有关联,只是静态显示;通过适配器列表项设置的文本,能保证后续下拉选择时的一致性。 setText()的第二个参数设为false,表示仅设置文本,不触发适配器的筛选逻辑,避免启动时自动弹出下拉菜单。
内容的提问来源于stack exchange,提问作者Elazar Halperin
相关产品推荐
相关产品推荐

