Myk Willis
Myk Willis

Reputation: 12879

ImageButton displays differently when created dynamically

I have a GridLayout-based View to which I am dynamically adding several ImageButtons. I'm trying to understand why the ImageButtons are styled correctly when I inflate them from a layout xml file, but not when I create them using the ImageButton constructor directly.

The GridLayout and ImageButtons were previously both defined in the same layout .xml file (and rendered as expected):

<ScrollView 
    style="@style/my_list_style"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="12dp">

        <GridLayout
            android:id="@+id/my_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center">

            <!-- These ImageButtons are being converted to dynamic. --> 
            <ImageButton
                style="@style/my_button_style"
                android:src="@drawable/image1" />

            <ImageButton
                style="@style/my_button_style"
                android:src="@drawable/image2" />

        </GridLayout>
    </LinearLayout>
</ScrollView>

To convert the ImageButtons to dynamic, I first removed them from the layout file and used code like the following to add them at runtime:

ImageButton imageButton = new ImageButton(context, null, R.style.my_button_style);
imageButton.setImageResource(R.drawable.image1);
parent.addView(imageButton);

But the buttons failed to render properly; they are not centered, and their sizes do not appear to be correct/uniform.

I then tried creating a new layout file, containing nothing but the ImageButton and its style:

<ImageButton
    style="@style/my_button_style"/>

When I inflate this layout into the GridView at runtime, everything looks as expected:

LayoutInflater inflater = LayoutInflater.from(context);
ImageButton imageButton = (ImageButton) inflater.inflate(
    R.layout.my_button_layout, parent, false);
imageButton.setImageResource(R.drawable.image1);
parent.addView(imageButton);

Why does inflating the view with LayoutInflator give different results than creating the button directly from its constructor?

Upvotes: 1

Views: 52

Answers (1)

azizbekian
azizbekian

Reputation: 62189

Because when you create ImageButton manually, you do not specify its parent, hence it doesn't know the layout params of its parent and can't be laid out as you expect.

On the other hand, when you inflate it via LayoutInflater, you are specifying the parent. Then correct layout params are being passed to children. That's why you see difference.

Have a look at detailed article by Dave Smith.

Upvotes: 1

Related Questions