刚开始学习自定义控件,按照教程一步一步的做下来,发现自定义属性并没有生效,于是又看了一次。
public class TestView extends View implements View.OnClickListener { private Paint mPaint; private Rect mRect; private int mNumber=20; private int mBackgroundColor; public TestView(Context context) { this(context, null); } public TestView(Context context, AttributeSet attrs) { this(context, attrs, 0);/*在看到这里的时候忽然想起来是复制的上面 this(context, null);然后在null后面添加了一个,0。并没有把attrs 传进去,所以自定义属性不可能生效*/ } public TestView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context,attrs); } private void init(Context context,AttributeSet attrs) { mPaint = new Paint(); mRect = new Rect(); setOnClickListener(this); TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.TestView); mBackgroundColor=typedArray.getColor(R.styleable.TestView_backgroundColor,Color.BLUE); mNumber=typedArray.getInt(R.styleable.TestView_text,210); Log.i("MYcolor",String.valueOf(R.styleable.TestView_backgroundColor)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(mBackgroundColor); canvas.drawCircle(getWidth() / 2, getWidth() / 2, getHeight() / 2, mPaint); // mPaint.setColor(Color.WHITE); mPaint.setTextSize(100); String text= String.valueOf(mNumber); mPaint.getTextBounds(text,0,text.length(),mRect); int textWidth = mRect.width(); int textHeight=mRect.height(); canvas.drawText(text,getWidth() / 2-textWidth/2, getHeight() / 2+textHeight/2,mPaint); } @Override public void onClick(View v) { //每点击一次减少1 if(mNumber>0){ mNumber--; }else{ mNumber=20; } invalidate(); } }