Android自定义view设置xml属性
一个圆形的自定义TextView,通过xml来设置背景颜色的属性
values/attrs
<declare-styleable name="MyCircleTextView">
<attr name="circleTint" format="color"/>
</declare-styleable>
在使用view的xml中
xmlns:app="http://schemas.android.com/apk/res-auto"
...
<MyCircleTextView
android:id="@+id/layout_1_1_750"
style="@style/functionItemCircleText"
android:text="1:1"
app:circleTint="@color/btn_login_purple_press" />
自定义的MyCircleTextView
public class MyCircleTextView extends android.support.v7.widget.AppCompatTextView {
private Paint paint;
float circleRadius = 100;
float centerX;
float centerY;
private String text = "测试";
int color;
Rect rect = new Rect();
public MyCircleTextView(Context context) {
super(context);
init();
}
public MyCircleTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyCircleTextView);
String string = typedArray.getString(R.styleable.MyCircleTextView_circleTint);
color = Color.parseColor(string);
init();
}
public MyCircleTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyCircleTextView);
String string = typedArray.getString(R.styleable.MyCircleTextView_circleTint);
color = Color.parseColor(string);
init();
}
private void init() {
paint = new Paint();
paint.setColor(color);
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
centerX = getWidth() / 2;
centerY = getHeight() / 2;
circleRadius = centerX;
//绘制一个圆形
canvas.drawCircle(centerX, centerY, circleRadius, paint);
super.onDraw(canvas);
}
}