ImageButton with different states images size
android, android-layout, imagebutton
Solution
Instead of using `ImageButton`, use `ImageView` because `ImageButton` cannot be resized itself based on `ImageSize`. `ImageView` is the best alternative way that i can suggest for your problem. Acheive that by the following way:
layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image_selection"/>
</RelativeLayout>
image_selection.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/default_image"/> //default_image.png is displayed when the Activity loads.
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/default_image_hover" /> //default_image_hover.png is an image displaed during Onclick of ImageView
<item android:state_focused="true"
android:drawable="@drawable/default_image_hover" />
<item android:state_focused="false"
android:drawable="@drawable/default_image"/>
</selector>
SampleActivity.java:
ImageView myImage= (ImageView)findViewById(R.id.image);
myImage.setOnClickListener(this);
Problem
How can I prevent an `ImageButton` from having a fixed size? The drawables used in the selector have different size, and I want the `ImageButton` to resize itself to match the image size. I've tried `adjustViewBounds` without success. ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" > <ImageButton android:id="@+id/picture_imagebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" android:src="@drawable/tab_background_selector" /> </RelativeLayout> ```