安卓:带有两张图片的按钮 | 对齐方式

4
我已经通过编程创建了此按钮,并且我能够使用以下代码在按钮上设置图标:

enter image description here

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

现在,我想在右上角添加另一张图片(icon),请参见下面的图片:

enter image description here

我尝试使用下面的代码添加两张图片:
Drawable icon = context.getResources().getDrawable(iconResourceId);
Drawable icon2 = context.getResources().getDrawable(iconResourceId2);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, icon2, null);

我得到了以下结果:

在这里输入图片描述

请问有谁能告诉我如何将其对齐到右上角?


尝试在按钮上使用相对ImageView,并将图像设置为ImageView。 - Jagjit Singh
RelativeLayout可以解决这个问题。 - V-rund Puro-hit
在xml中创建一个图层列表,其中包含按钮的背景和顶部的新图标。将该图层列表设置为按钮的背景。 - Jasper van de Klundert
@chappie112,我必须通过编程来实现它! - Abdul Aleem
是的兄弟,我想保留两张图片,一张在左侧,另一张在右上角 :) - Abdul Aleem
显示剩余3条评论
1个回答

0

你的代码将会像这样,其中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,那么它将显示两个图像,皇冠图像(右上角的图像)和按钮图标(左侧的图像),否则它将只显示按钮图标(左侧的图像)。 - Abdul Aleem
实际上我想把皇冠图像对齐到右上角! - Abdul Aleem
但这就是这段代码的作用(只需将hasNewUpdates()更改为您的VIP检查),但我们不是通过compoundDrawable(无法对齐图像)添加皇冠图像,而是通过背景来实现。此外,您的按钮是否具有渐变并不重要。它可以是任何东西,从图像到带有渐变的xml形状。 - Jasper van de Klundert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接