Skip to content

Instantly share code, notes, and snippets.

@sthewissen
Last active October 26, 2020 10:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sthewissen/2f54227793c8a512fefae6b779d18b28 to your computer and use it in GitHub Desktop.
Save sthewissen/2f54227793c8a512fefae6b779d18b28 to your computer and use it in GitHub Desktop.
A button renderer workaround for Samsung ripple problems
using System;
using Android.Content;
using Android.Content.Res;
using Android.Graphics.Drawables;
using MyProject.Droid.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Button), typeof(CustomButtonRenderer))]
namespace MyProject.Droid.Renderers
{
public class CustomButtonRenderer : ButtonRenderer
{
private GradientDrawable _normal, _pressed;
public CustomButtonRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var density = Math.Max(1, Resources.DisplayMetrics.Density);
var button = (Button)e.NewElement;
var borderRadius = button.CornerRadius * density;
var borderWidth = button.BorderWidth * density;
// Create a drawable for the button's normal state
_normal = new GradientDrawable();
_normal.SetColor(button.BackgroundColor.ToAndroid());
_normal.SetStroke((int)borderWidth, button.BorderColor.ToAndroid());
_normal.SetCornerRadius(borderRadius);
// Create a drawable for the button's pressed state
_pressed = new GradientDrawable();
var highlight = button.BackgroundColor.AddLuminosity(-0.05).ToAndroid();
_pressed.SetColor(highlight);
_pressed.SetStroke((int)borderWidth, button.BorderColor.ToAndroid());
_pressed.SetCornerRadius(borderRadius);
// Add the drawables to a state list and assign the state list to the button
var sld = new StateListDrawable();
sld.AddState(new int[] { Android.Resource.Attribute.StatePressed }, _pressed);
sld.AddState(new int[] { }, _normal);
Control.SetBackground(sld);
Control.SetTextColor(Element.TextColor.ToAndroid());
}
}
}
}
@chaoyebugao
Copy link

chaoyebugao commented Oct 26, 2020

There is a Problem: if I change Button's BackgroundColor on runtime, this code would broke, not working then. XF: 4.8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment