【问题标题】:Android Button with Drawable - Padding带有 Drawable 的 Android 按钮 - 填充
【发布时间】:2013-05-26 10:35:39
【问题描述】:

我想在左侧的按钮上添加一个可绘制图像并尝试了以下操作:

button = new Button(this);
button.setWidth(screen_dimens(0.25, "w")); //25% of screen width
button.setPadding(5, 5, 0, 5);
Drawable img = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);  

但我想在可绘制对象和按钮边框之间的左侧有一个填充。不幸的是,没有。
有什么帮助吗?

【问题讨论】:

  • 不能把左边的padding设置大一点吗?
  • 我尝试了 15 - 但没有区别
  • 好吧,好吧,这似乎是不可能的。我尝试的一切都失败了。我想我只会在图像文件中添加一个透明填充。但我对任何进一步的想法持开放态度:)
  • 为了其他人阅读本文,如果您设置了 'padding' 属性,它将执行您想要的操作。但是 paddingTop、paddingRight 等属性没有正确覆盖父级,也没有相同的效果。所以这种技巧在某些情况下可能对某些人有用,但不适用于我。

标签: java android button drawable padding


【解决方案1】:

使用此 API 调用:

public void setCompoundDrawablePadding (int pad)

【讨论】:

  • 但我认为这会在可绘制对象和文本之间添加填充。这不是我想要的
【解决方案2】:

这将生成文本+图像按钮(左侧的图像和之后的文本)

   <Button
   android:gravity="center_vertical"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"       
   android:id="@+id/button2"
   android:paddingLeft="20dp"
   style="@style/whiteText"
   android:onClick="openWhyAshoka"
   android:drawableLeft="@drawable/arrow"
   android:drawablePadding="50dp"
   android:text="Ankit" />

【讨论】:

  • 我尽了最大努力,但这个解决方案对我不起作用。你确定它有效吗?
【解决方案3】:

您必须通过更改 9 个切片内容区域或更改您的可绘制填充来为您的可绘制对象添加填充:

<padding
    android:bottom="10dp"
    android:left="10dp"
    android:right="10dp"
    android:top="10dp" />

如果您使用选择器,则必须将填充规则添加到每个可绘制状态。

【讨论】:

  • AFAIK 这是唯一不涉及代码的答案。虽然 OP 没有具体说明这就是他想要的,但这是我正在寻找的。 Android 需要解决这个问题 :(
【解决方案4】:

使用此代码:

Drawable image = (Drawable)getResources().getDrawable(R.drawable.onstar_mute_unmute_button_selector);

ImageButton button=(ImageButton)findViewById(R.id.imageButton);

button.setPadding(0,10,5,0);

button.setGravity(Gravity.RIGHT);

button.setBackground(image);

【讨论】:

    【解决方案5】:
      <Button
                android:id="@+id/otherapps"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_background"
                android:text="@string/other_apps"
                android:layout_weight="1"
                android:fontFamily="cursive"
                android:layout_marginBottom="10dp"
                android:drawableLeft="@drawable/ic_more"
                android:paddingLeft="8dp" //for drawable padding to the left
                android:textColor="@android:color/holo_red_light" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2013-03-02
      • 2021-06-06
      • 1970-01-01
      • 2011-10-23
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多