0

我刚开始使用自定义视图。我想创建一个视图并让它在布局中重复 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);
    }
}
4

1 回答 1

2

您没有为 LinearLayout 或子视图指定布局参数。我会layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);为每个 ThreeRects 实例使用相同的。您还需要onMeasure(int,int)在 ThreeRects 类中进行覆盖,以便 Android 可以弄清楚如何将其包含在布局中。可能因为您没有覆盖该方法,所以它们彼此重叠。

于 2013-09-16T13:55:54.070 回答