在布局中重复自定义视图

时间:2013-09-16 12:43:39

标签: android android-layout

我刚刚开始使用自定义视图。我想创建一个视图,并在布局中重复n次。

使用以下代码,自定义视图不会重复。更重要的是,如果我在标签和按钮之前插入它,那么它们不会被渲染。但是,如果我在其他两个控件之后插入自定义视图,则会显示它们。

我玩过onLayout等但是没有成功。

有人可以指出我正确的方向吗?

干杯。

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);
    }
}

1 个答案:

答案 0 :(得分:2)

您没有为LinearLayout或子视图指定布局参数。我会把layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);和每个ThreeRects实例一起使用。您还需要覆盖ThreeRects类中的onMeasure(int,int),以便Android可以弄清楚如何将其包含在布局中。也许他们被吸引到彼此之上,因为你没有覆盖那个方法。