动态添加Material TextInputLayout时遇Inflate Class错误求助
动态加载Material暴露式下拉框崩溃的问题解决
问题根源
崩溃核心原因是使用ApplicationContext的LayoutInflater加载布局,导致Material组件(如TextInputLayout内部的AppCompatTextView/MaterialTextView)无法获取当前页面的正确主题上下文。ApplicationContext的主题是全局默认配置,但Material组件初始化时需要依赖当前Activity/Fragment的主题上下文才能正常工作。
修复步骤
1. 替换LayoutInflater的获取方式
不要通过ApplicationContext获取LayoutInflater,直接使用Fragment/Activity自带的LayoutInflater(自动关联当前主题上下文):
- Fragment中直接用
layoutInflater属性 - Activity中用
getLayoutInflater()方法
2. 优化布局加载参数
加载布局时传入父容器stepsContainer并设置attachToRoot=false,确保布局继承父容器的布局参数,同时主题能正确传递:
val newView = layoutInflater.inflate(R.layout.timer, stepsContainer, false)
修改后的完整代码
private fun addStep() { when (currentOption) { getString(R.string.step) -> { val layoutInflater = layoutInflater stepsContainer = currentView.findViewById(R.id.recipe_steps_container) val newView = layoutInflater.inflate(R.layout.step, stepsContainer, false) newView.findViewById<ImageButton>(R.id.delete_step).setOnClickListener { view -> deleteStep(view) } val stepOne : LinearLayout = newView.findViewById(R.id.step_field_layout) stepOne.findViewById<EditText>(R.id.step_field).hint = getString(R.string.step_number, stepNumber) stepsContainer.addView(stepOne, stepNumber - 1) stepNumber++ } getString(R.string.timer) -> { val layoutInflater = layoutInflater stepsContainer = currentView.findViewById(R.id.recipe_steps_container) val newView = layoutInflater.inflate(R.layout.timer, stepsContainer, false) timeUnitsMenu = newView.findViewById(R.id.time_units_menu) val timer : LinearLayout = newView.findViewById(R.id.timer_field_layout) val timeUnits = resources.getStringArray(R.array.time_units) val arrayAdapter = ArrayAdapter(requireContext(), R.layout.dropdown_menu_item, timeUnits) timeUnitsMenu.setAdapter(arrayAdapter) stepsContainer.addView(timer, stepNumber - 1) stepNumber++ } } stepsScrollView.post { stepsScrollView.fullScroll(ScrollView.FOCUS_DOWN) } }
额外说明
- 替换为Spinner后仍出现类似错误,本质是同一个问题:ApplicationContext的LayoutInflater导致主题上下文不匹配
- Adapter使用
requireContext()是正确的,该方法返回当前Fragment关联的Activity上下文,符合组件的主题要求
内容的提问来源于stack exchange,提问作者Connor Smith
相关产品推荐
相关产品推荐

