java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.wi

 java.lang.ClassCastException:android.widget.LinearLayout$LayoutParams 
 cannot be cast to android.widget.AbsListView$LayoutParams

最近在团队项目中,用代码动态改变某种布局(组件)的高度时,会遇到如题所示的类转换异常。网上解释如下:
These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
So basically, if you are adding a view to another, you MUST set the LayoutParams of the view to the LayoutParams type that the parent uses, or you will get a runtime error.
大意说的是:如果你要将一个view添加到另一个布局中,你必须设定该View的布局参数为其父类所使用的布局参数类型。即要在代码中动态改变某组件的高度,其布局参数类型应该是其父类所使用的布局参数类型。

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);

此问题是在我是用 listView.addHeaderView(view);方法时候遇到的,本意在listView上面添加一个RadioGroup(内含两个RadioButton)
最终解决代码如下:

        //加载布局
        View viewHeader = LayoutInflater.from(getActivity()).inflate(R.layout.radio_to_activity, null);
        //初始化RadioGroup
        RadioGroup group = (RadioGroup) viewHeader.findViewById(R.id.group_rank);
        //在listView的头上添加View必须用listView类型的layoutParams给欲添加的view设置一下,便于布局管理器给它测量位置
        AbsListView.LayoutParams lp
                = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        group.setLayoutParams(lp);
        //将RadioGroup布局添加到listView顶部
        listView.addHeaderView(group);

这里写图片描述

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值