Search code examples
androidandroid-imageviewandroid-gridlayoutandroid-imagebutton

How to bind image to ImageButton dimensions?


I'm having trouble inserting a large image into ImageButtons which are children of a GridLayout...

I'm trying to build a tic-tac-toe board using a GridLayout which holds 9 identical ImageButtons. I am using images larger than the buttons themselves and everytime I set an image to a button (using setImageDrawable()) the buttons expands to fit the image size... My board looks like this:

 <GridLayout
            android:id="@+id/grid_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="3"
            android:rowCount="3">

            <ImageButton
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                />

            <ImageButton
                ...
                />

            <ImageButton
                ...
                />

            [...]
   </GridLayout>

I've tried adjusting the image size according to the buttons' measurements but getWidth() and getMeasuredWidth() both return 0 (probably because the buttons don't have a defined widht and height). Is there a way to make my image fit the button size without expanding the button itself?


Solution

  • You appear not to have a set width of height on the imagebuttons. Adjust the width or height as needed.

    Try

    <ImageButton
          android:layout_width="0dp"
          android:layout_height="0dp"
          android:layout_rowWeight="1"
          android:layout_columnWeight="1"
          android:adjustViewBounds="true"
          android:scaleType="fitCenter"
    />