package com.yarin.Android.Test; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class TestView extends View { private Paint mPaint = null; private Context mContext = null; /** * mTestView = new TestView(this); * setContentView(mTestView); * 如果在Activity中这样写,那么就需要实现这个构造函数 */ public TestView(Context context) { super(context); mContext = context; mPaint = new Paint(); } /** * setContentView(R.layout.main); * mTestView = (TestView)findViewById(R.id.mTestView); * 如果在Activity中这样写,那么就需要实现这个构造函数 */ public TestView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mPaint = new Paint(); TypedArray params = context.obtainStyledAttributes(attrs,R.styleable.TestView); //取得xml布局文件中所定义的背景 int backgroudId = params.getResourceId(R.styleable.TestView_backGround,0); if (backgroudId != 0) { setBackgroundResource(backgroudId); } //字体颜色 int textColor = params.getColor(R.styleable.TestView_textColor,0XFFFFFFFF); mPaint.setColor(textColor); //字体大小 float textSize = params.getDimension(R.styleable.TestView_textSize, 20); mPaint.setTextSize(textSize); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); //测试绘制一个矩形 canvas.drawRect(30, 50, 80, 90, mPaint); //绘制一个字符串 canvas.drawText("测试字符串", 50, 150, mPaint); } }
Android\OPhone自定义视图(View)
内容版权声明:除非注明,否则皆为本站原创文章。