【问题标题】:Android: Button with two images | alignmentAndroid:带有两个图像的按钮 |结盟
【发布时间】:2016-07-03 14:58:33
【问题描述】:

我已经以编程方式创建了这个按钮,我可以使用下面的代码设置icon

Drawable icon = context.getResources().getDrawable(iconResourceId);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

现在,我想在右上角再放一张图片(icon),请看下图:

我尝试使用以下代码添加两个图像:

Drawable icon = context.getResources().getDrawable(iconResourceId);
Drawable icon2 = context.getResources().getDrawable(iconResourceId2);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, icon2, null);

而且,我得到以下结果:

谁能告诉我,我怎样才能将它与右上角对齐?

【问题讨论】:

  • 尝试在按钮上使用相对 Imageview 并将图像设置为 imagview
  • RelativeLayout 可以解决问题
  • 在 xml 中创建一个图层列表,其中包含按钮的背景和顶部的新图标。将该图层列表设置为按钮的背景
  • @chappie112,我必须以编程方式实现它!
  • 您可以通过编程方式替换背景。还是你的意思是别的?

标签: android android-layout android-button


【解决方案1】:

您的代码将如下所示,其中btn_background 是您目前拥有的背景

    Button button = new Button(this);
    Drawable icon = context.getResources().getDrawable(iconResourceId);
    button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
    button.setText("Test");

    if (hasNewUpdates()) {
        button.setBackgroundResource(R.drawable.btn_background_with_icon);
    } else {
        button.setBackgroundResource(R.drawable.btn_background);
    }

这就是btn_background_with_icon 的样子

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_background"/>
    <item android:gravity="right" android:bottom="72dp" android:drawable="@drawable/ico_info"/>
</layer-list>

【讨论】:

  • 你还是没有明白我的意思,按钮的背景是由渐变色创建的,这两个图像是单独的图像,如果用户是VIP,那么它将显示两个图像,皇冠图像(右上角角图像)和按钮图标(左侧图像),否则它将显示按钮图标(左侧图像)
  • 其实我想把皇冠图片对齐右上角!
  • 但这就是这段代码的作用(只需使用您的 VIP 检查更改 hasNewUpdates()),而不是通过 CompoundDrawable 添加皇冠图像(我们无法对齐图像)我们这样做通过背景。此外,您的按钮是否具有渐变也没关系。它可以是任何东西,从图像到带有渐变的 xml 形状。
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 2011-10-11
相关资源
最近更新 更多