8
我目前正試圖將以下XML以編程方式創建,以便我可以在整個項目中根據需要設置頂角和底角。這是一個簡單的圖層列表,它有兩個矩形;一個在另一個之上。我想用這個作爲幾個不同觀點的背景,所以結果比例很重要。以編程方式創建帶圓角的圖層列表
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:bottom="20dp">
<shape android:shape="rectangle" >
<size android:height="20dp" />
<solid android:color="#969595" />
<corners
android:radius = "0dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
</shape>
</item>
<item android:top="20dp">
<shape android:shape="rectangle" >
<size android:height="20dp" />
<solid android:color="#7B7979" />
<corners
android:radius = "0dp"
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp" />
</shape>
</item>
</layer-list>
這種方法的工作,但我需要一個單獨的XML每個形狀取決於我是否要在頂部,底部,兩者或無邊角圓潤。
我目前嘗試創建相同的drawable只產生了兩個矩形,一個在另一個之上。我無法弄清楚如何設置矩形的位置。無論形狀的邊界是怎樣設置的,我都看不到任何可見的變化。任何建議將不勝感激。
// Usage:
setBackgroundDrawable(new DualColorStateDrawable(0, 10f));
...
private final int topColorUnselected = Color.RED;
private final int bottomColorUnselected = Color.GREEN;
private final int topColorSelected = Color.YELLOW;
private final int bottomColorSelected = Color.BLUE;
private final int m_nZERO_RADIUS = 0;
class DualColorStateDrawable extends StateListDrawable
{
public NYWTableViewCellStateDrawable(float topRadius, float bottomRadius){
addState(new int[] { -android.R.attr.state_pressed },
createListWithSelectedState(false, topRadius, bottomRadius));
addState(new int[] { android.R.attr.state_pressed },
createListWithSelectedState(true, topRadius, bottomRadius));
}
public Drawable createListWithSelectedState(
boolean isSelected, float topRadius, float bottomRadius){
int topColor, bottomColor;
if (isSelected) {
topColor = topColorSelected;
bottomColor = bottomColorSelected;
} else {
topColor = topColorUnselected;
bottomColor = bottomColorUnselected;
}
int x = 10;
int y = 10;
int width = 20;
int height = 20;
RoundRectShape _rrsTopShape =
new RoundRectShape(getRadii(topRadius, m_nZERO_RADIUS), null, null);
CustomShapeDrawable _csdTopShape =
new CustomShapeDrawable(_rrsTopShape, topColor);
RoundRectShape _rrsBottomShape =
new RoundRectShape(getRadii(m_nZERO_RADIUS, bottomRadius), null, null);
CustomShapeDrawable _csdBottomShape =
new CustomShapeDrawable(_rrsBottomShape, bottomColor);
_csdBottomShape.setBounds(x, y, x + width, y + height);
return new LayerDrawable(new Drawable[] {_csdTopShape, _csdBottomShape});
}
private float[] getRadii(float top, float bottom)
{
return new float[] { top, top, //
top, top, //
bottom, bottom, //
bottom, bottom //
};
}
class CustomShapeDrawable extends ShapeDrawable {
private final Paint fillpaint;
public CustomShapeDrawable(Shape s, int fill) {
super(s);
fillpaint = new Paint(this.getPaint());
fillpaint.setColor(fill);
}
@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
shape.draw(canvas, fillpaint);
}
}
}