Warm tip: This article is reproduced from stackoverflow.com, please click
android xml

android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

发布于 2020-03-27 10:30:12

I'm getting exception when i do following:

findViewById(R.id.some_container).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50)); 

But when I change to new LinearLayout.LayoutParams that's ok. If LinearLayout.LayoutParams is child of ViewGroup.LayoutParams that why I can't cast?

Questioner
pushandpop
Viewed
79
W0rmH0le 2019-07-03 23:53

All LinearLayout is also a ViewGroup but not all ViewGroup is a LinearLayout. That's why you can't cast a ViewGroup to a LinearLayout

You can create a LinearLayout.LayoutParams from a ViewGroup.LayoutParams as follows:

LinearLayout.LayoutParams params = 
    new LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50));

However, a simple cast is impossible.