2016-03-17 25 views
4

我创造了这个按钮编程,我能够通过使用下面的代码来设置上的iconAndroid:带有两个图像的按钮|对准

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); 

和,我得到下面的结果:

enter image description here

谁能告诉我,我该如何调整它的右上角?

+0

尝试使用按钮和设置相对的ImageView Image to imagview –

+0

RelativeLayout将执行该操作 –

+0

在xml中创建一个包含按钮背景和顶部新图标的层列表。将该层列表设置为您的按钮背景 –

回答

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> 
+0

你仍然没有得到我的观点,按钮的背景是由渐变色创建的,这两个图像是独立的图像,如果用户是VIP,那么它会显示两个图像,皇冠图像(右上角图像)和按钮图标(左侧图像),否则它会显示按钮图标(左侧图像) –

+0

实际上我想对齐皇冠形象的右上角! –

+0

但是这就是代码所做的事情(只需要用你的VIP检查来更改hasNewUpdates()),而不是通过compoundDrawable(我们无法对齐图像)添加皇冠图像,而是通过背景来完成。此外,如果您的按钮有渐变,则无关紧要。它可以是任何从图像到具有渐变的xml形状。 –