How to set Width and Height of FrameLayout dynamically android?
Asked Answered
P

4

7

I am trying to set the width and height of 2 frame layouts which are the containers for 2 fragments, both being children of a Linear Layout.

However whenever I set width and height of the layout with

frameLayout.setLayoutParams(new FrameLayout.LayoutParams(100,100);

it is resulting in a class cast Exception

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

Purposeless answered 14/10, 2016 at 8:8 Comment(0)
D
15

use this method ...

.setLayoutParams(new LinearLayout.LayoutParams(100,100);

instead of your method ....

.setLayoutParams(new FrameLayout.LayoutParams(100,100)

Note:- ClassCastException problem happen when your class is different other class, you want to cast....

Dufrene answered 14/10, 2016 at 8:10 Comment(1)
you are welcome ... and remember the exception for next timeDufrene
P
10

This answer is actually complementary, as some people already explained the solution, but I wanted to clarify the question further more.

As mentioned above, you must set the parameters to the PARENT view and not to the view itself. You said that the FrameLayouts are inside LinearLayouts, so you must set the parameters for that.

That is the reason why you got the exception

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

The compiler is telling you exactly that, you cannot cast FrameLayout parameters to a LinearLayout.

From Android documentation:

LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.

Hope that clarifies the question even more!

Pyelography answered 21/10, 2016 at 2:29 Comment(0)
N
3

You can use the following code."gameframe" is the name of the frameLayout.

ViewGroup.LayoutParams params = gameFrame.getLayoutParams();
params.width = New_width;
params.height = New_height;      
gameFrame.setLayoutParams(params);
Nonesuch answered 22/5, 2020 at 1:11 Comment(0)
K
1

The exception report gives you a hint. It looks like the parent layout of your FrameLayout is a LinearLayout. So, you need to set LinearLayout params for your FrameLayout. Try the following:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(your_width, your_height);
frameLayout.setLayoutParams(lp);
Kreutzer answered 14/10, 2016 at 8:11 Comment(2)
Yes I agree absolutely, I also noticed that you cannot set the layout params if your parent layout is a relative layoutPurposeless
@JayakrishnanMenon glad that helped.Kreutzer

© 2022 - 2024 — McMap. All rights reserved.