2011-12-23 110 views
1

我在xml文件中定義了這種形狀,並且需要在代碼中創建它,但難住了。Android:我將如何在代碼中創建此資源形狀?

我假設我想實例化一個RoundRectShape並將它的屬性設置爲xml中的屬性,但屬性排列得不太好。

RoundRectShape(float[] outerRadii, RectF inset, float[] innerRadii) 

我的XML形狀只有1個半徑,現在RectF和RoundRectShape具有設置填充或顏色沒有選項?

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#00FFFFFF" /> 
    <stroke android:width="2dp" android:color="#FFFFFFFF" /> 
    <padding android:left="7dp" android:top="7dp" 
      android:right="7dp" android:bottom="7dp" /> 
    <corners android:radius="4dp" /> 
</shape> 

回答

2

您需要創建自定義繪製siomething像下面

示例代碼

public class CustomDrawable extends ShapeDrawable{ 
    Paint fillpaint, strokepaint; 
    private static final int WIDTH = 2; 

@Override 
protected void onDraw(Shape shape, Canvas canvas, Paint paint) { 
    // TODO Auto-generated method stub 
// super.onDraw(shape, canvas, paint); 
    fillpaint = this.getPaint(); 
    strokepaint = new Paint(fillpaint); 
    strokepaint.setStyle(Paint.Style.STROKE); 
    //to set stroke width and color instead of <stroke android:width="2dp" android:color="#FFFFFFFF" /> 
    strokepaint.setStrokeWidth(WIDTH); 
    strokepaint.setARGB(255, 255, 255, 255); 

    shape.draw(canvas, fillpaint); 
    shape.draw(canvas, strokepaint); 

} 
}