Reputation: 185
I have activity with button inside GridLayout that is defined like this:
<Button
android:id="@+id/btnOpion4"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:layout_width="0dp"
android:layout_height="0dp"
android:drawableStart="@drawable/btnSend"/>
To be able to show icon on that button i had to create drawable xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_send"
android:state_pressed="true" />
<item android:drawable="@drawable/ic_send"
android:state_focused="true" />
<item android:drawable="@drawable/ic_send" />
</selector>
And all of this is working just fine...
Problem is, how can i change image from code behind? For example if user click on some option, then change icon on this button?
EDIT:
Can I find that drawable by it's ID, and change icon?
Something like var btnsendDraw = FindViewById(Resource.Drawable.btnSend);
Upvotes: 0
Views: 196
Reputation: 9356
You can accomplish that by using the SetCompoundDrawablesWithIntrinsicBounds
method found in the Button
class.
In your case, I would create another drawable file with my other background:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_sent"
android:state_pressed="true" />
<item android:drawable="@drawable/ic_sent"
android:state_focused="true" />
<item android:drawable="@drawable/ic_sent" />
</selector>
and let's call it: btnSent
.
Now in your code, when you want to change the image just do:
var drawable = GetDrawable(Resource.Drawable.btnSent);
btn1.SetCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
This method gets the 4 different Drawables: left, top, end & bottom in this specific order. Since you only want to replace the start you will set the first parameter.
Note: left
and start
are "the same".
More about this method here
At the end you should have something like this:
Hope this helps.-
Upvotes: 2