2011-12-24 7 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); 

    } 

} 

EDIT: 解決策だった:

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