【发布时间】:2011-04-29 01:13:15
【问题描述】:
我正在尝试创建一个带有圆角(和选择的背景颜色)的视图,我可以使用不同的背景颜色重复使用它;很难解释,所以这是我的代码:
/app/src/com/packagename/whatever/CustomDrawableView.java
package com.packagename.whatever;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.PaintDrawable;
import android.util.AttributeSet;
import android.view.View;
public class CustomDrawableView extends View {
private PaintDrawable mDrawable;
int radius;
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.RoundedRect);
radius = a.getInteger(R.styleable.RoundedRect_radius, 0);
}
public CustomDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
mDrawable = new PaintDrawable();
}
protected void onDraw(Canvas canvas) {
mDrawable.setCornerRadius(radius);
mDrawable.draw(canvas);
}
}
这是显示自定义组件的 XML: /app/res/layout/test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ny="http://schemas.android.com/apk/res/com.packagename.whatever"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="10dp">
<com.packagename.whatever.CustomDrawableView
android:id="@+id/custom"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#b80010"
ny:radius="50"
/>
</LinearLayout>
我希望红色框有 50 像素的圆角,但正如您所见,它没有:
我的想法是我可以轻松地更改 XML 中的背景颜色,并自动获得一个漂亮的圆角视图,而无需创建多个可绘制对象。
感谢您的帮助!
【问题讨论】: