为什么都是ViewGroup的LayoutParams,也会报cannot be cast to android.view.ViewGroup$MarginLayoutParams?

今天是周六,分享一首许哲佩的一起摇摆吧,一起享受在这华丽的声音和梦幻的歌词里吧

同时分享一张在上海拍的照片
为什么都是ViewGroup的LayoutParams,也会报cannot be cast to android.view.ViewGroup$MarginLayoutParams?_第1张图片

正文

今天在代码里要动态改变 SurfaceView 的尺寸时,因为父布局是 FrameLayout ,自然就使用了 如下写法

val layoutParams = FrameLayout!!.layoutParams
      layoutParams.height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, resources.displayMetrics).toInt()
      layoutParams.width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, resources.displayMetrics).toInt()

   SurfaceView!!.layoutParams = layoutParams
   

最后运行的时候 , 没想到这样写居然会报错了???

java.lang.ClassCastException: android.view.ViewGroup L a y o u t P a r a m s c a n n o t b e c a s t t o a n d r o i d . v i e w . V i e w G r o u p LayoutParams cannot be cast to android.view.ViewGroup LayoutParamscannotbecasttoandroid.view.ViewGroupMarginLayoutParams

异常说的是两个是不同类型的LayoutParams ,但明明都是ViewGroup的LayoutParams呀,而且log上没有标明位置,实际是为什么呢

其实就是不去新建一个LayoutParams,而是从原来的View中直接获取LayoutParams。

val layoutParams = FrameLayout!!.layoutParams

改为
val layoutParams = recordUVCView!!.layoutParams

改完运行结果没有出现异常了。

因为,当一个View已经有了LayoutParams,是不能再次添加一个新创建的LayoutParams的,如果这样操作就会报这样的错。
一个小小的坑,希望大家看到后可以避免。
祝大家周末愉快

你可能感兴趣的:(Android笔记,Kotlin学习,android,java,安卓)