androidx.media2.widget.VideoView填充报错TextureView不支持背景Drawable
问题引发原因
- androidx.media2.widget.VideoView内部依赖
VideoTextureView实现视频渲染,该控件继承自系统原生TextureView,而TextureView本身设计上就不支持设置任何背景drawable,只要检测到有背景drawable就会抛出UnsupportedOperationException。 - 你在布局中给VideoView设置了
android:background="@android:color/transparent",透明色本质是ColorDrawable类型的背景drawable,会被系统传递到内部的TextureView,最终触发inflate阶段崩溃。 - 即使你没有主动设置背景,如果你当前应用的主题中配置了默认的View背景属性,也会触发该问题。
解决方案
- 方案1:直接删除VideoView布局中的
android:background属性。androidx.media2.VideoView默认的渲染背景就是透明的,无需额外设置即可实现透明效果。 - 方案2:如果需要给视频播放区域添加背景色/背景图,给VideoView外层套一层父布局(如FrameLayout、ConstraintLayout),将背景属性设置到父布局上即可,参考示例:
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent"> <androidx.media2.widget.VideoView android:id="@+id/videoView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:visibility="visible" /> </FrameLayout>
- 方案3:如果崩溃是因为App全局主题默认给所有View添加了背景属性,可在VideoView布局中显式添加
android:background="@null",该属性会通知系统不要给当前控件设置任何背景drawable,不会触发TextureView的限制。
内容的提问来源于stack exchange,提问作者Wiktor Nizio
相关产品推荐
相关产品推荐

