Xamarin Android Button Styles

One of the best UX designs you can do for a user is give them feedback, especially when clicking on a button.  In mobile development, this no exception!  In Android this is relatively easy by setting the text color to a drawable resource.  For example lets say you have the following drawable xml:

buttonText.xml


<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" />
  <item android:state_focused="true" android:state_pressed="true" android:color="#000000" />
  <item android:state_focused="false" android:state_pressed="true" android:color="#000000" />
  <item android:color="#ffffff" />
</selector>

What we’re trying to achieve is changing the text color of the button throughout the different states the button may go through (i.e. when you click on the button).  The following next examples show you how to apply the Resource using Java then in C# using Xamarin.Android.

Java

Button button = (Button) findViewById(R.Id.Button1);

button.setTextColor(getColorStateList().getColor(R.drawable.buttonText));

C#

Button button = new Button(this.Context);

var buttonDrawable = Resources.GetLayout(Resource.Drawable.buttonText);

button.SetTextColor(Android.Content.Res.ColorStateList.CreateFromXml(Android.Content.Res.Resoures.System, buttonText));

There you have it! Setting the text color of a button using Xamarin Android. I wasn’t able to find an exact description on how to do this using c#, however, using Java’s implementation I was able to port it over into the C# world.

Until next time, Happy coding!