Xamarin Border Radius AppCompat

我只是一个虾纸丫 提交于 2019-12-23 07:59:07

问题


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.



来源:https://stackoverflow.com/questions/37126414/xamarin-border-radius-appcompat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!