I am trying to set the height of toolbar programmatically by this way:
toolbar.setLayoutParams(new Toolbar.LayoutParams(LayoutParams.MATCH_PARENT, 42));
toolbar.setMinimumHeight(42);
But it causes fatal exception with this log -> android.widget.relativelayout$layoutparams cannot be cast to android.support.v7.Toolbar$layoutparams
I also try this variant:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) toolbar.getLayoutParams();
params.height = 42;
toolbar.setLayoutParams(params);
toolbar.setMinimumHeight(42);
It does not give an exception but also it does not work and toolbar gets it's default bigger height in stead of my defined. But of course setting the parameters in xml
works, but I need to set the height in java too.
So please help me to solve the problem.
Try this -
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mToolbar.getLayoutParams();
layoutParams.height = 42;
mToolbar.setLayoutParams(layoutParams);
It works fine for me.
If above code still doesn't work, try adding this line at the end -
mToolbar.requestLayout();
The above line will force your Toolbar to remeasure everything. Your code might not be working because you are trying to change the height after layout is inflated. In that case you need to force your View to remeasure everything. Take a look at following methods for more info - requestLayout(), invalidate() and forceLayout(). While altering the LayoutParams on go, these three methods comes handy but with a great price. If your Layout is very heavy and have lots of child views in it, calling any of these method will affect the performance of your app specially on lower end devices. So make sure you use these methods really carefully.
And the crash you mentioned is happening because your Toolbar is a child view of your root view and your root view is RelativeLayout. Hope it helps.
Also please don't follow the answer by Silambarasan Poonguti as its bit ambiguous. LayoutParams casting is needed if you are trying to access child LayoutParams. Even View has its own LayoutParams, you have to cast it to parent or root LayoutParams for ex. if your Toolbar is a child view of RelativeLayout then casting LayoutParams to Toolbar.LayoutParams will crash the app and you have to cast the LayoutParams to RelativeLayout.LayoutParams