首页 > 解决方案 > Xamarin Android 中自定义视图中的错误解析 XML 错误

问题描述

在这里,我从 View 类扩展了 TransparentCircleView 类,但我无法在 .axml 文件中使用该视图。给出错误解析 XML 时出错:格式不正确(无效令牌) FieldStar.Droid E:\Projects\FieldStar\FieldStar.Droid\Resources\layout\activity_home.axml 44

透明圆形视图.cs

namespace FieldStar.Droid.Views
{

[Register("FieldStar/Droid/Views/TransparentCircleView")]
public class TransparentCircleView : View
{
    private readonly string DEFAULT_BACKGROUND_COLOR = "#ffffff";
    private readonly string DEFAULT_FOREGROUND_COLOR = "#000000";
    private Paint _backgroundPaint, _foregroundPaint;
    public TransparentCircleView(Context context) : base(context)

    {
        Init();
    }

    public TransparentCircleView(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        Init();
    }

    public TransparentCircleView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
    {
        Init();
    }

    public TransparentCircleView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
    {
        Init();

    }

    protected TransparentCircleView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {

    }

    protected override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);
        int radius = -1;
        if (Width < Height)
        {
            radius = (Width - PaddingLeft - PaddingRight) / 2;
        }
        else
        {
            radius = (Height - PaddingTop - PaddingBottom) / 2;
        }

        //Background Circle
        canvas.DrawRect(0, 0, Width, Height, _backgroundPaint);

        //Foreground Circle
        canvas.DrawCircle(Width / 2, Height / 2, radius,_foregroundPaint);
    }

    private void Init()
    {
        _backgroundPaint = new Paint();
        _backgroundPaint.AntiAlias = true;
        _backgroundPaint.SetStyle(Paint.Style.Fill);
        _backgroundPaint.Color = Color.ParseColor(DEFAULT_BACKGROUND_COLOR);

        //Foreground View
        _foregroundPaint = new Paint();
        _foregroundPaint.AntiAlias = true;
        _foregroundPaint.SetStyle(Paint.Style.Fill);
        _foregroundPaint.Color = Resources.GetColor(Android.Resource.Color.Transparent);
    }

    public void SetBackgroundColor(string color)
    {
        _backgroundPaint.Color = Color.ParseColor(color);
        Invalidate();
    }

    public void SetForegroundColor(string color)
    {
        _foregroundPaint.Color = Color.ParseColor(color);
        Invalidate();
    }
}

}

标签: xamarin.android

解决方案


此错误的最常见原因是未确保组件的命名空间路径为小写。您说返回的错误是“Error Error parsing XML: not well-formed (invalid token) FieldStar.Droid ”这一事实往往表明这是问题所在。确保您在 xml 中引用组件,如下所示:

<fieldStar.droid.views.TransparentCircleView
.....
.....
/>

推荐阅读