Reputation: 5907
I'm just starting out with custom views. I'd like to create a view and have it repeat n times down a layout.
With the following code, the custom view is not repeating. What's more, if I insert it before the label and the button, then they are not rendered. However, if I insert the custom view after the other two controls, then they are shown.
I've played around with onLayout etc however have had no success.
Can someone please point me in the right direction?
Cheers.
public class ThreeRects : View
{
Paint _boxPaint;
Paint _boxPaint2;
Paint _boxPaint3;
public ThreeRects (Context context): base(context)
{
this._boxPaint = new Paint (PaintFlags.AntiAlias);
this._boxPaint.SetStyle (Paint.Style.Fill);
_boxPaint.Color = Color.Aqua;
this._boxPaint2 = new Paint (PaintFlags.AntiAlias);
this._boxPaint2.SetStyle (Paint.Style.Fill);
_boxPaint2.Color = Color.Red;
this._boxPaint3 = new Paint (PaintFlags.AntiAlias);
this._boxPaint3.SetStyle (Paint.Style.Fill);
_boxPaint3.Color = Color.Blue;
}
protected override void OnDraw (Android.Graphics.Canvas canvas)
{
var rect = new RectF (0, 0, 50, 50);
var rect2 = new RectF (50, 50, 100, 100);
var rect3 = new RectF (100, 100, 150, 150);
canvas.DrawRect (rect, this._boxPaint);
canvas.DrawRect (rect2, this._boxPaint2);
canvas.DrawRect (rect3, this._boxPaint3);
base.OnDraw (canvas);
}
}
[Activity (Label = "FertPinAndroid", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate(bundle);
var layout = new LinearLayout (this);
layout.Orientation = Orientation.Vertical;
var aLabel = new TextView (this);
aLabel.Text = "Hello World";
var aButton = new Button (this);
aButton.Text = "Say Hello";
aButton.Click += (sender, e) => {
aLabel.Text = "Hello from the button";
};
layout.AddView (new ThreeRects (this));
layout.AddView (aLabel);
layout.AddView (aButton);
layout.AddView (new ThreeRects (this));
layout.AddView (new ThreeRects (this));
SetContentView (layout);
}
}
Upvotes: 0
Views: 637
Reputation: 93591
You didn't specify layout params for the LinearLayout or the sub-views. I would put layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
and for each of the ThreeRects instances use the same. You also need to override onMeasure(int,int)
in the ThreeRects class so Android can figure out how to include it in a layout. Maybe they are getting drawn on top of each other because you didn't override that method.
Upvotes: 2