2016-03-17 26 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形狀。 –