以编程方式更改按钮样式

时间:2017-08-01 10:33:03

标签: c# xamarin xamarin.android

我想在android上绘制材质设计Flat Button,因为我制作了这个渲染器:

public class NativeFlatButtonRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        var oldElement = e.OldElement as NativeFlatButton;

        if (oldElement != null)
        {
        }

        var newElement = e.NewElement as NativeFlatButton;
        if (newElement != null)
        {
            Control.SetBackgroundResource(Android.Resource.Style.WidgetMaterialButtonBorderless);
        }
    }
}

并抛出 Android.Content.Res.Resources + NotFoundException:资源ID#0x1030259
当我改为

if (newElement != null)
{
   var button = new AppCompatButton(Context, null, Android.Resource.Style.WidgetMaterialButtonBorderlessColored);
   SetNativeControl(button);
}

它的绘图但没有命令等。那么我如何在Android上用渲染器绘制平面按钮?

1 个答案:

答案 0 :(得分:0)

这很安静。以下是创建本机控件的ButtonRenderer方法:

protected override Android.Widget.Button CreateNativeControl()
{
   return new Android.Widget.Button(this.Context);
}

所以我只需要覆盖它,并且有完整的渲染器:

public class NativeFlatButtonRenderer : ButtonRenderer
{
    protected override Android.Widget.Button CreateNativeControl()
    {
        var button = new AppCompatButton(Context, null, Android.Resource.Style.WidgetMaterialButtonBorderlessColored);
        return button;
    }
}