Android Studio Eel XML预览不显示自定义组件,提示缺失类
Android Studio Electric Eel 自定义控件预览空白并提示「Missing classes」问题解决
升级Android Studio至Electric Eel | 2022.1.1版本后,XML布局中TextView、Button等基础控件可正常显示预览,但自定义组件CustomTextView预览空白,同时提示「Missing classes」错误。
相关代码
主Activity布局文件
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.example.webviewdeeplink.CustomTextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is Test Text" android:textSize="24sp" app:font="RobotoCondensed-LightItalic.ttf" app:layout_constraintBottom_toTopOf="@id/button" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
自定义组件类
class CustomTextView : androidx.appcompat.widget.AppCompatTextView { constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super( context!!, attrs, defStyle ) { init(attrs) } constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) { init(attrs) } constructor(context: Context?) : super(context!!) { init(null) } private fun init(attrs: AttributeSet?) { if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView) val fontName = a.getString(R.styleable.CustomTextView_font) try { if (fontName != null) { val myTypeface = Typeface.createFromAsset( context.assets, "fonts/$fontName" ) setTypeface(myTypeface) } } catch (e: Exception) { e.printStackTrace() } a.recycle() } } }
可能的解决办法
- 切换布局渲染引擎:在布局预览顶部工具栏找到「Render Options」,取消勾选「Use AndroidX Runtime Rendering」,切回旧渲染引擎。Electric Eel的新渲染引擎对部分自定义控件兼容性较差,这是最常见的临时修复方案。
- 清理IDE缓存并重启:通过
File → Invalidate Caches...选择「Invalidate and Restart」,很多预览类问题能通过清理缓存解决。 - 优化自定义控件构造逻辑:去掉构造函数中的非空断言
!!,改用安全调用逻辑(比如context ?: return),避免预览时因上下文异常导致渲染失败。 - 检查自定义属性定义:确认
res/values/attrs.xml中CustomTextView的属性定义是否正确,确保app:font对应的属性存在且命名完全匹配。 - 降级AGP版本:如果上述方法无效,可尝试将Android Gradle Plugin版本降级到7.2.0这类稳定版本,部分用户反馈降级后预览恢复正常。
已知问题说明
该问题属于Android Studio Electric Eel版本的已知兼容性问题,核心是新布局渲染引擎对自定义控件的支持不完善,官方后续补丁更新大概率会修复此问题。
内容的提问来源于stack exchange,提问作者void pointer
相关产品推荐
相关产品推荐

