我正在跟踪教程链接“ https://code.tutsplus.com/tutorials/android-sdk-creating-custom-views--mobile-14548”,但无法为圆圈上色。我创建了一个自定义视图LovelyView,并尝试在onDraw方法上对其进行充气。
Lovelyview是自定义视图,并为custom:circleColor分配了颜色
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:custom="http://schemas.android.com/apk/res-com.example.narroju.lovelyactivity"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LovelyActivity">
<com.example.narroju.lovelyactivity.LovelyView
android:id="@+id/custView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="5dp"
custom:circleColor="#ff0099"
custom:circleLabel="Hello"
custom:labelColor="#ffff66" />
</RelativeLayout>
在可爱的活动中,我无法使circlecolor的drawCircle颜色膨胀
package com.example.narroju.lovelyactivity;
import android.content.Context;
import android.view.View;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
public class LovelyView extends View {
//circle and text colors
private int circleCol, labelCol;
//label text
private String circleText;
//paint for drawing custom view
private Paint circlePaint;
public LovelyView(Context context, AttributeSet attrs) {
super(context, attrs);
//paint object for drawing in onDraw
circlePaint = new Paint();
//get the attributes specified in attrs.xml using the name we included
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.LovelyView, 0, 0);
try {
//get the text and colors specified using the names in attrs.xml
circleText = a.getString(R.styleable.LovelyView_circleLabel);
circleCol = a.getInteger(R.styleable.LovelyView_circleColor, 0);//0 is default
labelCol = a.getInteger(R.styleable.LovelyView_labelColor, 0);
} finally {
a.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
//draw the View
super.onDraw(canvas);
//get half of the width and height as we are working with a circle
int viewWidthHalf = this.getMeasuredWidth() / 2;
int viewHeightHalf = this.getMeasuredHeight() / 2;
//get the radius as half of the width or height, whichever is smaller
//subtract ten so that it has some space around it
int radius = 0;
if (viewWidthHalf > viewHeightHalf)
radius = viewHeightHalf - 10;
else
radius = viewWidthHalf - 10;
circlePaint.setStyle(Style.FILL);
circlePaint.setAntiAlias(true);
//set the paint color using the circle color specified
circlePaint.setColor(circleCol);
canvas.drawCircle(viewWidthHalf, viewHeightHalf, radius, circlePaint);
}
}