是否可以通过java更改按钮上的drawable?
实施例;我有一个这样的按钮。
<Button
style="@style/Buttons"
android:id="@+id/butFavTeam"
android:drawableBottom="@drawable/venue"/>
我想用我的drawable目录中的另一个更改当前的drawableBottom图像。
答案 0 :(得分: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);
我希望有所帮助。
答案 1 :(得分:3)
刚刚找到它。
Drawable myIcon = this.getResources().getDrawable(R.drawable.myVenue);
butFavTeam.setCompoundDrawablesWithIntrinsicBounds(null, null, null, myIcon);
答案 2 :(得分:1)
顺便说一下......确保你不小心使用方法setCompoundDrawables()。它采用与setCompoundDrawablesWithIntrinsicBounds()相同的参数,但显然也期待一些边界细节。
我因此而懒散地接受了第一种预先输入方法。我发布这个,以防你也无法弄清楚图像没有显示的原因。