ImageButton具有不同的状态图像大小

gde*_*nte 9 android imagebutton android-layout

如何防止ImageButton固定尺寸?选择器中使用的drawable具有不同的大小,我希望ImageButton自己调整大小以匹配图像大小.

我试过adjustViewBounds没有成功.

<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>
Run Code Online (Sandbox Code Playgroud)

Ava*_*i Y 6

而不是使用ImageButton,ImageView因为ImageButton无法根据自身的大小调整使用ImageSize.ImageView是我可以为您的问题建议的最佳替代方式.通过以下方式实现:

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

SampleActivity.java:

  ImageView myImage= (ImageView)findViewById(R.id.image);
    myImage.setOnClickListener(this);
Run Code Online (Sandbox Code Playgroud)