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

今天是周六,分享一首许哲佩的一起摇摆吧,一起享受在这华丽的声音和梦幻的歌词里吧
同时分享一张在上海拍的照片

正文
今天在代码里要动态改变 SurfaceView 的尺寸时,因为父布局是 FrameLayout ,自然就使用了 如下写法
复制代码
最后运行的时候 , 没想到这样写居然会报错了????<font color=#FF0000 size=5>java.lang.ClassCastException: android.view.ViewGroupMarginLayoutParams</font>
异常说的是两个是不同类型的 LayoutParams ,但明明都是 ViewGroup 的 LayoutParams 呀,而且 log 上没有标明位置,实际是为什么呢
其实就是不去新建一个 LayoutParams,而是从原来的 View 中直接获取 LayoutParams。
将
复制代码
改完运行结果没有出现异常了。
因为,当一个 View 已经有了 LayoutParams,是不能再次添加一个新创建的 LayoutParams 的,如果这样操作就会报这样的错。一个小小的坑,希望大家看到后可以避免。祝大家周末愉快
版权声明: 本文为 InfoQ 作者【程思扬】的原创文章。
原文链接:【http://xie.infoq.cn/article/8577ae3df133aaa46fbc63c22】。文章转载请联系作者。
评论