我正在使用Xamarin.Android,我想从List
填充由TouchEvent
填充的圈子。
这是我的代码:
public class Ceiling : View
{
private List<PointF> _points;
private Canvas _canvas;
private Paint paint;
protected Ceiling(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public Ceiling(Context context) : base(context)
{
_points = new List<PointF>();
paint = new Paint
{
Color = Color.Red
};
paint.SetStyle(Paint.Style.Fill);
Touch += OnTouch;
}
public Ceiling(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public Ceiling(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
}
public Ceiling(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
{
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
if (_canvas == null)
{
_canvas = canvas;
Background = new PaintDrawable(Color.AliceBlue);
canvas.SetViewport(Width, Height);
}
base.OnDraw(canvas);
if (_points.Count > 0)
{
foreach (var point in _points)
canvas.DrawCircle(point.X, point.Y, 10, paint);
}
}
private void OnTouch(object sender, TouchEventArgs e)
{
switch (e.Event.Action)
{
case MotionEventActions.Down:
{
var point = new PointF(e.Event.GetX(), e.Event.GetY());
if (!_points.Contains(point))
{
_points.Add(point);
_canvas.DrawCircle(point.X, point.Y, 10, paint);
}
break;
}
}
}
}
仅在已定义_points
时才有效。我怎样才能做到这一点?
答案 0 :(得分:1)
您有多个构造函数,其中只有一个初始化私有变量。你确定构造函数是被调用的那个(我假设这是从布局初始化的)?
在任何情况下,最好将初始化移动到单独的方法,以便可以从所有构造函数中调用它:
protected Ceiling(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
// need to call init here as well?
}
public Ceiling(Context context) : base(context)
{
Init();
}
public Ceiling(Context context, IAttributeSet attrs) : base(context, attrs)
{
Init();
}
public Ceiling(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
Init();
}
public Ceiling(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
{
Init();
}
private void Init()
{
_points = new List<PointF>();
this.paint = new Paint
{
Color = Color.Red
};
this.paint.SetStyle(Paint.Style.Fill);
Touch += OnTouch;
}