【问题标题】:In Android, how to place image at center on a button without stretching?在Android中,如何将图像放在按钮的中心而不拉伸?
【发布时间】:2016-05-12 01:43:18
【问题描述】:

在 Android 布局文件中,我有一个按钮。我想为按钮显示一个没有任何文本的图像。我遇到的问题是,图像被拉伸以覆盖整个按钮区域。我希望将按钮放置在按钮的中心而不是拉伸,而不会对图像造成任何扭曲。

<Button
    android:layout_width="38dp"
    android:layout_height="match_parent"
    android:background="@drawable/icon_more"
    android:id="@+id/button"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true" />

现在,它看起来像这样:

它是水平拉伸的,这不是我想要的。

【问题讨论】:

  • 使用ImageView,设置它的背景并使用它的onClickListener。

标签: android image button layout


【解决方案1】:

使用 ImageButton 是您的另一种选择。你可以试试:

    <ImageButton
        android:layout_width="38dp"
        android:layout_height="match_parent"
        android:src="@drawable/icon_more"
        android:scaleType="centerInside"
        />

灵活组合 layout_width、layout_height 和 scaleType 属性,助你打造出色的 UI

【讨论】:

  • 你的建议对我有用。我不知道我需要的 ImageButton。
【解决方案2】:

在某些主题中,有一些默认属性(minWidthminHeight...)与Button。所以这导致你的背景正在伸展。我建议你使用ImageView 就像@ShamasS 评论一样,或者如果你想使用Button,尝试在你的xml 中添加这些属性:

<Button
...
android:minHeight="0dp"
android:minWidth="0dp"/>

或以编程方式使用setMinHeight(0)setMinWidth(0)

希望有所帮助!

【讨论】:

    【解决方案3】:

    使用这个:

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="XXdp"
            android:onClick="onClick"
            android:drawableTop="@drawable/yourimage
            android:text="Button" />
    

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 2016-02-21
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      相关资源
      最近更新 更多