zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams

Android to Cannot be cast Widget LayoutParams RelativeLayout
2023-06-13 09:12:27 时间

大家好,又见面了,我是你们的朋友全栈君。

FrameLayout的父控件是一个LinearLayout控件,问题出在,LinearLayout为子控件分配空间的时候,获取FrameLayout的LayoutParams的必须为LinearLayout.LayoutParams,而非FrameLayout.LayoutParams。

简单的举个栗子说明一下:最外层有ReLativeLayout A,里面有两个LinearLayout B、C,而B中又有一个一个FrameLayout D。如果要在代码里设置B的LayoutParams,B的LayoutParams要为RelativeLayout.LayoutParams。

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);   B.setLayoutParams(params);

而D要设置的话,需要:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);   params.weight = 8;   D.setLayoutParams(params);

而笔者是直接使用的最外层的RelativeLayout,它的外层不是RelativeLayout了,导致笔者的代码一直报错

java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams

所以笔者就在最外层的RelativeLayout放入了一个RelativeLayout_inside,然后再把自定义view放入RelativeLayout_inside,现在RelativeLayout_inside的外层就是RelativeLayout了,错误也就消失了。

现记录,引以为戒

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160833.html原文链接:https://javaforall.cn