Android 将图像添加到按钮而不调整大小

Android 将图像添加到按钮而不调整大小,android,Android,我在一个按钮上添加了一个名为“星”的图片,图片出现了,但它使按钮变大了 <Button android:id="@+id/latest_photoB" android:layout_height="87dp" android:layout_weight="1" android:background="#dcdcdc" android:drawableTop="@drawable/star" android:text="Latest Photos" android:textSize="10d

我在一个按钮上添加了一个名为“星”的图片,图片出现了,但它使按钮变大了

<Button
android:id="@+id/latest_photoB"
android:layout_height="87dp"
android:layout_weight="1"
android:background="#dcdcdc"
android:drawableTop="@drawable/star"
android:text="Latest Photos"
android:textSize="10dp"
android:textColor="#000000"  />

我尝试了很多不同的方法,比如把它做成一个
imagebutton


我尝试了
android:background=image
,但没有任何效果。如何添加图片并保持其大小不变?

也许您正在寻找android:setAdjustViewBounds=“false”按钮的默认背景可绘制使用所谓的九块补丁。它将根据按钮内容的大小调整自身大小。按钮是一种特殊的文本视图,它的四个面上都可以附着可拉伸(复合可拉伸)。文本和复合绘图表构成了按钮的内容,这就是按钮调整大小的原因

复合绘图是对视图层次结构的优化,因为它减少了非常常见场景的视图数量,但听起来您想要一个ImageView+一个按钮,其中ImageView的响应方式与您单击按钮时的响应方式相同

在这种情况下,将按钮包装在一个布局中,其中包含一个ImageView,并将onClickListener设置在布局上,而不是按钮上。摆脱:

android:layout_weight="1"
而是为按钮定义一个特定的大小:

android:layout_height="87dp"
android:layout_width="50dp"

希望这有帮助。

如果希望按钮具有图像背景,请执行以下操作:

<Button
    android:id="@+id/latest_photoB"
    android:layout_height="87dp"
    android:layout_width="87dp"
    android:background="@drawable/star"
    android:text="Latest Photos"
    android:textSize="10dp"
    android:textColor="#000000"  />


如果按钮应为固定尺寸,则不需要布局重量。另外,您还没有定义
layou-weight
属性。我已经设置了它
87dp
。根据需要更改。如果不设置按钮的高度和宽度,Android按钮将包装内容(与图像大小相同)。这样试试

<Button
android:id="@+id/latest_photoB"
android:layout_height="87dp"
android:layout_width="87dp"
android:layout_weight="1"
android:background="@drawable/star"
android:text="Latest Photos"
android:textSize="10dp"
android:textColor="#000000"  />


您想让它与什么保持相同大小?如果设置了背景,则设置其应保持该大小的高度和宽度。我希望按钮保持相同大小,一旦显示图像,它就会变大。layout_width=“87dp”不起作用-它更改了我的按钮的大小。@Dianewer是否有要为按钮指定的大小?您应该使用该尺寸代替
87dp