5

我需要做的是让背景图像填充按钮的自然大小,就像没有指定背景并显示默认的灰色背景图像一样。但相反,我的按钮会放大到背景图像而不是文本的大小。

以前有一个问题,但没有人有解决方案。

按钮:

在此处输入图像描述

<Button
    android:id="@+id/morebtn"
    style="@style/CustomButton"
    android:text="More" />

我有这个自定义按钮样式(灰色按钮是 9 补丁):

<resources>
    <style name="CustomButton" parent="@android:style/TextAppearance">
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:layout_marginLeft">10dip</item>
        <item name="android:layout_marginRight">10dip</item>
        <item name="android:layout_marginBottom">10dip</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_centerInParent">true</item>
        <item name="android:background">@drawable/greybutton</item>
        <item name="android:textSize">20sp</item>
    </style>
</resources>

现在它会在宽度方向填满屏幕,尽管被告知要 wrap_content。当我从 Button 样式中删除android:background时,按钮会缩小以按预期包裹文本。

有谁知道为什么我的背景图片不像默认的按钮背景?

4

4 回答 4

5

你为什么不使用 ImageButton 代替:

<ImageButton android:src="@drawable/greybutton"
            android:scaleType="fitCenter" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

然后您可以使用scaleType属性调整缩放比例。唯一的缺点是您不能设置任何文本。

于 2011-07-27T21:08:22.647 回答
2

该死的。我有一个尚未转换为 9patch 的 hdpi drawable,并且由于某种原因,即使在我的 mdpi 屏幕上,它也被应用而不是 mdpi drawables 文件夹中的那个。毕竟,背景缩放实际上确实按预期工作。对不起!

(因此,如果您在浏览此问题时遇到类似问题,请检查您的 drawables 文件夹以确保您正在绘制您认为的内容。另外:可能希望确保您的九个补丁中的内容边界是适当的大小。请注意,它们与可拉伸边界不同。)

于 2011-07-27T21:33:22.860 回答
1

您可以尝试使用 dip 对按钮的高度和宽度进行硬编码。如果您需要更改按钮上的文本,这将是一个问题,但它应该可以限制按钮扩展到图像的大小。当然大图会让按钮变大..宽度/高度是wrap_content,图片显然是内容的一部分...尝试硬编码宽度/高度参数。

于 2011-07-27T21:00:32.600 回答
1

将这两项添加到您的 CustomButton 样式中

<item name="android:minWidth">0dp</item> 
<item name="android:minHeight">0dp</item>
于 2014-05-20T12:26:54.247 回答