Skip to content

Instantly share code, notes, and snippets.

@cmeeren
Last active February 12, 2018 08:29
Show Gist options
  • Select an option

  • Save cmeeren/a795d0ad40100f4e23ef95699bf59cec to your computer and use it in GitHub Desktop.

Select an option

Save cmeeren/a795d0ad40100f4e23ef95699bf59cec to your computer and use it in GitHub Desktop.
Android flat button support in Xamarin.Forms
<Application
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:MyApp.Controls;assembly=MyApp"
x:Class="MyApp.App">
<Application.Resources>
<ResourceDictionary>
<!-- Implicit style - BackgroundColor works on iOS, but not Android (https://bugzilla.xamarin.com/show_bug.cgi?id=60392),
hence the need for the custom renderer in the first place. -->
<Style TargetType="controls:FlatButton">
<Setter Property="BackgroundColor" Value="Transparent" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
namespace MyApp.Controls
{
using Xamarin.Forms;
public class FlatButton : Button
{
}
}
using Xamarin.Forms;
using MyApp.Android;
using MyApp.Controls;
[assembly: ExportRenderer(typeof(FlatButton), typeof(FlatButtonRenderer))]
namespace MyApp.Android
{
using global::Android.Content;
using global::Android.Util;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Application = global::Android.App.Application;
using ButtonRenderer = Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer;
using Color = global::Android.Graphics.Color;
internal class FlatButtonRenderer : ButtonRenderer
{
public FlatButtonRenderer(Context context)
: base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (this.Control == null) return;
TypedValue value = new TypedValue();
Application.Context.Theme.ResolveAttribute(Resource.Attribute.selectableItemBackground, value, true);
this.Control.SetBackgroundResource(value.ResourceId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment