Xamarin Border Radius AppCompat

2019-06-16 21:44发布

问题:

It seems that the BorderRadius attribute is not working when including AppCompat in the project.

I tried to create a custom render like this discussed here, but it didn't work:

namespace Xamarin.Forms
{
    public class CustomButton : Button  
    {
        public CustomButton():base()
        {   
        }

        protected override void OnParentSet()
        {
            base.OnParentSet();
        }
    }
}

In the Android project:

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace CalculateurMadelin.Droid.Renderers
{
        public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
    { }
}

回答1:

You can load an Android drawable in your custom renderer to define the background on your AppCompat.Button:


[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace AppCompatRender.Droid
{
    public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                Control.SetBackgroundResource(Resource.Drawable.CustomButtonBackground);
            }
        }
    }
}

Add a new Resources/Drawable that matches the name you are using in your SetBackgroundResource (i.e.. CustomButtonBackground.axml), in this I am setting a corner radius of the rectangle as 10dp:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <corners android:radius="10dp" />
</shape>



回答2:

That's true, custom renderers for Button (and also Picker, Switch, Frame etc.) are not called with AppCompat.

Link with the investigation: https://forums.xamarin.com/discussion/comment/180130/#Comment_180130

Link describing a solution: http://www.isosoft.org/taoffi/post/2016/03/26/Xamarin-forms-so-you-lost-your-rounded-buttons (corrected link error) The cleaner way is to inherit from a Button and setup a custom renderer for inherited control.