Setting background drawable “SelectableItemBackground” for Button in Xamarin Android Material Design

Now I know we all love the latest Material Design on Android! Luckily the awesome Xamarin team, made it available in Xamarin.Android as soon as Google released it. (Kudos Xamarin team!)

Watch out !

There was this one time, I wanted to make a Button background color invisible, but we all know as soon as you set the background color/resource you will be loosing the default Material Design properties for the Button, as it will override the default material design properties. So this is what I did, and unfortunately I ended up with a non-material boring button.

buttonView.Background = new ColorDrawable(Xamarin.Forms.Color.Transparent.ToAndroid());

 

Yep, it did give me a Transparent background button, but it had lost it’s Material Design properties. 😦 All it’s “Ripple Effect” click properties were disappeared.

Solution ?

Yep and lucky enough I found the solution by roaming around the “cyberspace” and thanks to my previous native Android dev experience. 😉

In Android material design properties we have this value attribute called “SelectableItemBackground” , which holds the background drawable resource for the default transparent ripple effect click properties. All we need to do is, set this to our Button’s Background resource. 😀

Le Code Snippet!

Yes it’s pretty straightforward in native android, but how about Xamarin Android ? Yep let me show you. 😉

In Xamarin Android we could access the above attribute at, “Android.Resource.Attribute.SelectableItemBackground“, yep lucky enough Xamarin had a great documentation. lol So here goes the implementation.

int[] attrs = new int[] { Android.Resource.Attribute.SelectableItemBackground };
// Retrieving the style attribute
TypedArray typedArray = this.ApplicationContext.ObtainStyledAttributes(attrs);
int backgroundResource = typedArray.GetResourceId(0, 0);

// Setting the button background resource
buttonView.SetBackgroundResource(backgroundResource);
// Clear the array
typedArray.Recycle();

 

Alright, as you can see above (hope you read through my comments in the code snippet), we are retrieving the SelectableItemBackground style and manually setting it to the Button background resource.

Le XML Snippet ?

Oh no I wouldn’t leave that out.. 😉 setting this in XML is pretty much same as native Android.

 android:background="?android:attr/selectableItemBackground"

 

VOILA ! 😀

No go on and play around fellas! 😉

Cheers!

Stay Awesome! 😀

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.