【问题标题】:Center a drawable in a Button with background and no text在具有背景且没有文本的 Button 中将可绘制对象居中
【发布时间】:2020-09-02 12:37:19
【问题描述】:

我的 Android 应用中有几个按钮。它们每个看起来都像这样:

<Button
    android:id="@+id/button_1"
    android:drawableTop="@drawable/an_icon"
    android:background="@drawable/a_background"
    android:layout_width="size_dp"
    android:layout_height="size_dp">
</Button>

当然,我是 Android 开发新手,但我不知道如何在我的按钮中将可绘制对象居中。我已经为按钮及其容器以及 drawablePadding 尝试了不同的 drawableLocations、边距和填充,但我似乎无法完成它。有没有办法在不放弃另一个视图的按钮的情况下使可绘制对象居中?

【问题讨论】:

  • 您是否使用图像作为背景可绘制对象,如果是,请尝试使用 imageView 并将其作为 src 传递,它将自动适合按钮。我发现一个链接有时会说您的代码将其居中并且它在真实设备上可见,eclipse 错过了这一点。也试试这个。 stackoverflow.com/questions/21711468/…
  • 是的,背景图片是一个有点大的“空按钮”,在应用程序的许多其他地方都用到了它。出于这个原因,我为 Button 设置了硬 dp 宽度和高度值(无 wrap_content)。我也没有使用图形可视化工具——只是一个测试设备,以确保我的所有更改都反映了它的实际外观。另外,你的意思是链接到这个问题吗?大声笑

标签: android button


【解决方案1】:

最简单的解决方案是使用ImageButton 小部件:

<ImageButton
    (...)
    android:background="@drawable/a_background"
    android:src="@drawable/an_icon"
    />

【讨论】:

    【解决方案2】:

    有没有办法让drawable居中而不放弃Button

    因此您可以使用ImageView 来同时拥有(背景和可绘制),如下所示:(因此无需使用按钮)

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/an_icon"
        android:background="@drawable/a_background" />
    

    对于OnClick 的ImageView:

    findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    
        }
    });
    

    【讨论】:

    • 这个问题是它放弃了可点击的功能,我不太想重新实现。但是,如果我无法找到其他解决方案,这可能是可行的方法。
    • ImageView 提供与 Button 相同的可点击功能。
    • 虽然它不像在 Button 视图中更改属性那么容易,但它成功了。谢谢。
    【解决方案3】:

    试试这个:

      <Button
            android:id="@+id/button_1"
            android:drawableTop="@drawable/an_icon"
            android:background="@drawable/a_background"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="151dp">
        </Button>
    

    【讨论】:

    • 当我需要重新定位按钮的内容时,对齐和边距属性只会相对于其容器移动按钮。
    猜你喜欢
    • 2013-03-25
    • 2020-04-25
    • 1970-01-01
    • 2011-04-20
    • 2013-09-18
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多