You need to enable JavaScript to run this app. Android自定义View搭配ViewBinding触发InflateException异常问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Android自定义View搭配ViewBinding触发InflateException异常问题求解

解决方案

一、InflateException 报错修复

该报错与ViewBinding无直接关联,本质是自定义View实例化过程中无法解析主题属性?attr/primaryTextColorDefault,仅因为Binding inflate阶段才会触发XML中控件实例化,所以看起来是ViewBinding导致的问题。
修复步骤如下:

  • 检查自定义View的Kotlin构造方法写法,必须正确使用@JvmOverloads注解,且父类构造调用时传入正确的默认样式属性,不要直接传0:
// 正确写法,以CustomButton为例
class CustomButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    // 继承AppCompatButton则传入对应默认样式属性,不同父类对应不同值
    defStyleAttr: Int = androidx.appcompat.R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
    // 原有业务逻辑不变
}
  • 禁止使用applicationContext解析主题属性,所有属性读取必须通过View自身携带的Context配合obtainStyledAttributes实现:
// 自定义View内读取属性的正确写法
init {
    val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, defStyleAttr, 0)
    val textColor = typedArray.getColor(R.styleable.CustomTextView_android_textColor, Color.BLACK)
    typedArray.recycle()
    setTextColor(textColor)
}
  • 确认当前Activity使用的主题中已明确定义primaryTextColorDefault属性,无主题配置缺失。

二、无独立XML布局的自定义View适配ViewBinding方案

这类纯逻辑/纯绘制类、不需要嵌套子View的自定义View,完全不需要单独创建XML布局、也不需要为自定义View本身生成Binding类,适配逻辑和系统原生控件完全一致:

  1. 父布局XML中保留原有自定义View的声明方式,添加id即可:
<!-- activity_main.xml 示例 -->
<com.yourproject.widget.CustomButton
    android:id="@+id/custom_submit_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="提交" />
  1. 直接通过父布局生成的Binding访问自定义View,类型自动匹配无需强转:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    // 直接访问自定义View实例
    binding.customSubmitBtn.setOnClickListener {
        // 业务逻辑
    }
}

内容的提问来源于stack exchange,提问作者Markus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 23:15:02