因此,我創建了這個名爲rounded_rect的可繪製xml文件。我最初將它的顏色設置爲紅色。不過,我希望能夠在我的佈局文件中更改此顏色。通過佈局更改xml可繪製文件中形狀的顏色
rounded_rect.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#ffff1900"/>
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp"/>
<stroke android:width="4dp"
android:color="#000000"/>
</shape>
我的佈局文件包含一個名爲ItemView控件的自定義視圖。我的一個自定義屬性是背景顏色。
<custonview.android.example.com.customview.ItemView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:imagePath="@drawable/yes"
custom:text="Yes"
custom:backgroundColor="#000000"
android:layout_row="0"
android:layout_column="0"
android:background="@drawable/rounded_rect_green"
android:layout_margin="30dp" />
目標是能夠將我的可繪製文件中的顏色更改爲我在佈局文件中分配的顏色。這是我的ItemView.java文件
public class ItemView extends View {
//attributes of item view
private Drawable drawable;
private String text;
private int backgroundColor;
private int width, height;
private Paint paint;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.ItemView, 0, 0);
try {
text = a.getString(R.styleable.ItemView_text);
backgroundColor = a.getInteger(R.styleable.ItemView_backgroundColor, 0);
drawable = a.getDrawable(R.styleable.ItemView_imagePath);
} finally {
}
paint = new Paint();
width = drawable.getMinimumWidth()/2;
height = drawable.getMinimumHeight()/2;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
//positions the image in the middle horizontally and a little above the text below
drawable.setBounds(width/4, height/4 - 50, width - (width/4),
height - (height/4) - 50);
drawable.draw(canvas);
paint.setTextSize(100);
paint.setColor(Color.BLACK);
canvas.drawText(text, width/2 -
paint.measureText(text, 0, text.length())/2, height - 50, paint);
}
}
- 也許我在考慮它。免費在你的答案中有創意。預先感謝您