Android:如何完全通过代码创建AutoCompleteTextView(无XML)
问题分析与解决方案
你当前代码的主要问题在于未正确应用Material组件的样式属性、布局参数配置错误,以及缺少关键的关联设置,导致轮廓框无法正常显示。以下是具体的修复点和完整代码:
缺失的配置项
- TextInputLayout布局参数错误:宽度设为
WRAP_CONTENT而非MATCH_PARENT,且未添加XML中定义的边距。 - 未关联LabelFor:TextInputLayout的提示文本未与AutoCompleteTextView绑定,影响样式和 accessibility。
- AutoCompleteTextView样式缺失:未应用XML中的内边距、文字大小,也未启用暴露式下拉菜单的Material样式。
- 圆角单位错误:直接使用像素值设置圆角,未转换为dp导致跨设备显示不一致。
- 下拉菜单样式未启用:AutoCompleteTextView未配置为Material风格的暴露式下拉菜单。
修复后的完整代码
首先添加dp转px的工具方法:
private int dpToPx(int dp) { return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics() ); }
然后替换原有的动态创建代码:
// 创建带Material暴露式下拉样式的AutoCompleteTextView AutoCompleteTextView textView = new AutoCompleteTextView( new ContextThemeWrapper(getContext(), R.style.Widget_MaterialComponents_AutoCompleteTextView_ExposedDropdownMenu) ); textView.setId(View.generateViewId()); // 设置AutoCompleteTextView的布局参数和样式 LinearLayout.LayoutParams tvLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f // 匹配XML中的layout_weight ); textView.setLayoutParams(tvLayoutParams); textView.setPadding(dpToPx(14), dpToPx(14), dpToPx(14), dpToPx(14)); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); // 创建带轮廓框下拉菜单样式的TextInputLayout TextInputLayout textInputLayout = new TextInputLayout( new ContextThemeWrapper(getContext(), R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox_ExposedDropdownMenu) ); textInputLayout.setId(View.generateViewId()); // 设置TextInputLayout的布局参数和样式 LinearLayout.LayoutParams tilLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ); int marginHorizontal = dpToPx(32); int marginVertical = dpToPx(5); tilLayoutParams.setMargins(marginHorizontal, marginVertical, marginHorizontal, marginVertical); textInputLayout.setLayoutParams(tilLayoutParams); textInputLayout.setHint("Select Week"); textInputLayout.setLabelFor(textView.getId()); // 绑定提示文本与输入框 textInputLayout.setStartIconDrawable(R.drawable.ic_round_calendar_today_24); textInputLayout.setStartIconTintList(ContextCompat.getColorStateList(getContext(), R.color.black)); // 设置圆角(转换为px) int cornerRadius = dpToPx(5); textInputLayout.setBoxCornerRadii(cornerRadius, cornerRadius, cornerRadius, cornerRadius); // 填充下拉选项并设置默认文本 ArrayList<String> weeksArray = new ArrayList<>(); for (int i = 1; i <= 8; i++) { weeksArray.add(String.valueOf(i)); } ArrayAdapter<String> weeksAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, weeksArray); textView.setAdapter(weeksAdapter); textView.setText(String.valueOf(currWeek), false); // 添加到视图层级 textInputLayout.addView(textView); this.addView(textInputLayout);
额外注意事项
确保你的应用主题继承自Material Components主题(如Theme.MaterialComponents.DayNight.DarkActionBar),否则Material样式将无法正常生效。
内容的提问来源于stack exchange,提问作者Learn2Code
相关产品推荐
相关产品推荐

