2010-08-31 28 views
2

是否可以通過java更改按鈕上的drawable?用java更改drawableBottom

示例;我有一個這樣的按鈕。

<Button 
style="@style/Buttons" 
android:id="@+id/butFavTeam" 
android:drawableBottom="@drawable/venue"/> 

我想更改當前drawableBottom圖像與另一個從我的繪圖目錄。

+0

除了下面的答案,是否有任何方式在API <3.0中做到這一點? – 2012-07-15 20:32:28

回答

7

有你看着這個方法:

/* 
Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds. 
*/ 
public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, Drawable top, Drawable right, Drawable bottom) 

試試這個:

/*remember to first clear the callback of the drawable you are replacing to prevent memory leaks... 
* Get the Drawables for the button by calling: myButton.getCompoundDrawables(), then loop through that calling myOldDrawable.setCallback(null); 
* e.g:*/ 

for(Drawable myOldDrawable : myButton.getCompoundDrawables()) 
{ 
    myOldDrawable.setCallback(null); 
} 

//use null where you don't want a drawable 
myButton.setCompoundDrawablesWithIntrinsicBounds(null,null,null, myNewDrawable); 

我希望幫助。

+3

NULL值是**不正確**。如果您不想要Drawable,請使用0 .setCompoundDrawablesWithIntrinsicBounds(0,0,0,myIcon); [Source](http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds%28int,%20int,%20int,%20int%29) – 2011-10-04 15:46:59

+5

null是正確的。在他的例子中,他傳遞了實際的Drawables,所以null是該方法版本的正確「無價值」。還有另一個版本,大概你在想,你傳遞了四個可繪製的id值(即int),並且0是正確的事情,通過你不想要Drawable的地方。 – Zulaxia 2012-04-01 16:41:04

+0

**兩種**方法都是正確的。請參閱http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds%28android.graphics.drawable.Drawable,%20android.graphics.drawable.Drawable,%20android.graphics.drawable.Drawable,% 20android.graphics.drawable.Drawable%29 and http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds%28int,%20int,%20int,%20int%29 – 2014-12-21 12:45:45

3

剛剛找到它。

Drawable myIcon = this.getResources().getDrawable(R.drawable.myVenue); 
butFavTeam.setCompoundDrawablesWithIntrinsicBounds(null, null, null, myIcon); 
1

順便說一下...確保您不會意外地使用方法setCompoundDrawables()。它採用與setCompoundDrawablesWithIntrinsicBounds()相同的參數,但它顯然也期望一些邊界細節。

我因此陷入了獵物之中,因爲我懶洋洋地接受了第一種預先輸入的方法。我發佈這個,以防你無法弄清楚爲什麼圖像不顯示。