In my app I'm using android.support.v7.widget.Toolbar
.
Left half of the toolbar always acts as back button.
Right half is different for different activities. Sometimes it's just text, sometimes a button. So I inflate the right half with views programmatically.
Toolbar
<android.support.v7.widget.Toolbar>
...
... <LinearLayout
android:id="@+id/left_LL"/>
...
<LinearLayout
android:id="@+id/right_LL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:orientation="horizontal" />
</android.support.v7.widget.Toolbar>
I'm inflating this view in right_LL:
child_button.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/right_IB"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/save"
android:background="@null"
android:onClick="onRightHeaderButton"
android:scaleType="fitXY" />
I'm adding it programatically like this:
right_LL.addView(inflater.inflate(R.layout.child_button,
null, false));
So the problem is that the button occupies half the screen. It's original dimensions are 512x512.
I thought that maybe the LayoutParams are somehow getting reset, so I also tried
final float scale = getResources().getDisplayMetrics().density;
int pixels = (int) (30 * scale + 0.5f);
right_IB = (ImageButton) right_LL.findViewById(R.id.right_IB);
right_IB.setLayoutParams(new ViewGroup.LayoutParams(
pixels,pixels));
it gave this exception:
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
Any help will be greatly appreciated.
When you call
inflater.inflate(R.layout.child_button, null, false)
, you are passing innull
for the parent view - this causes anylayout_
attributes to be ignored (as those attributes are only used by the parent view) - see this Google+ post for more details.Instead, you should use
This causes your
child_button
layout to be inflated properly for its parent layout,right_LL
, and automatically added (that's what thetrue
does).