将自定义矩形添加到自定义RelativeLayout

时间:2011-12-24 11:31:52

标签: android

我有一个自定义RelativeLayout,我想动态创建矩形。

它们没有显示在我当前的代码中,但我不知道原因是什么。

自定义RelativeLayout:

public class DrawView extends RelativeLayout {

    public DrawView(Context context) {
        super(context);
        setFocusable(true);

        this.addView(new Rectangle(this.getContext()));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);   

    }

自定义矩形:

public class Rectangle extends View {

    public Rectangle(Context context) {
        super(context);
    }

    public Rectangle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Rectangle(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle); 
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);

        canvas.drawRect(new Rect(), paint);

    }

}

编辑: 解决方案是:

public class Rectangle extends View {

    public Rectangle(Context context) {
        super(context);
        init();
    }

    public Rectangle(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public Rectangle(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle); 
        init();
    }

    private void init() {
        this.setBackgroundResource(R.drawable.rectangle);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = 150;
        int height = 50;

        setMeasuredDimension(width, height);
    }

}


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="5sp"/>
    <gradient
        android:angle="315"
        android:startColor="#FFFF6666"
        android:endColor="#FFFF1111"
        android:type="linear"
        />
</shape>

1 个答案:

答案 0 :(得分:2)

我认为您缺少设置Shape LayoutParams。尝试创建Rectangle对象,设置其宽度+高度,然后将其添加到RelativeLayout:D