Reputation: 322
I want to set my LinearLayout's parameters after all of the views' parameters are calculated.
I am trying to set LinearLayout's height related to the parent view's height. And parent view's height is calculated according to its layout_weight
, so I get the height by getMeasuredHeight();
My code :
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
RelativeLayout lay = (RelativeLayout) findViewById(R.id.alt);
LinearLayout bar = (LinearLayout) findViewById(R.id.barLay);
int layH = lay.getMeasuredHeight();
int barH = layH / 4;
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
params.height = barH;
bar.setLayoutParams(params);
}
Eclipse Debugger stops the program at this line;
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
I can't find what could be the problem? Am I doing something wrong to set params?
Upvotes: 0
Views: 3554
Reputation: 1274
The type of LayoutParams are actually set by the parent of the view, so bar.getLayoutParams() should be returning an object of type RelativeLayout.LayoutParams
. With an explicit cast to LinearLayout.LayoutParams
I'd expect your logcat to contain a line like this:
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
Changing it to this should do the trick:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bar.getLayoutParams();
or, since height is in the base class, don't cast it at all:
ViewGroup.LayoutParams params = bar.getLayoutParams();
Upvotes: 1
Reputation: 322
After @LocHa asked me the type of the layouts, I try changing the parent layout's type to LinearLayout which was RelativeLayout, and finally it worked for me.
Upvotes: 0
Reputation: 1867
Try changing this
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
to this
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bar.getLayoutParams();
Upvotes: 0