2011-12-24 52 views
1

我有一个自定义的RelativeLayout,我想在其中动态创建矩形。将自定义矩形添加到自定义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> 

回答

2

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