虽然Android已经自带了很多强大的控件,但是仍然不能满足开发的需求,自定义view已经成为了开发者必须要掌握的最重要的技能之一。
首先介绍主要步骤: 1、继承自View创建自定义控件; 2、如有需要自定义View属性,就在values/attrs.xml中定义属性集; 3、在xml中引入命名控件,设置属性; 4、在代码中读取xml中的属性,初始化视图; 5、测量视图大小; 6、绘制视图内容。
public class SimpleImageView extends View { //画笔 PRivate Paint mPaint; //宽 private int mWidth; //高 private int mHeight; private Drawable mDrawable; public SimpleImageView(Context context) { this(context, null); } public SimpleImageView(Context context, AttributeSet attrs) { super(context, attrs); //根据属性初始化 initAttrs(attrs); //初始化画笔 mPaint = new Paint(); mPaint.setAntiAlias(true);//抗锯齿 } private void initAttrs(AttributeSet attrs) { if (attrs != null) { TypedArray array = null; try { array = getContext().obtainStyledAttributes(attrs, R.styleable.SimpleImageView); //根据图片id获取drawable对象 mDrawable = array.getDrawable(R.styleable.SimpleImageView_src); //测量Drawable对象的宽高 measureDrawable(); } finally { if (array != null) { array.recycle(); } } } } private void measureDrawable() { if (mDrawable == null) { throw new RuntimeException("drawable不能为空"); } mWidth = mDrawable.getIntrinsicWidth(); mHeight = mDrawable.getIntrinsicHeight(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(mWidth, mHeight); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDrawable == null) { return; } //绘制图片 canvas.drawBitmap(ImageUtils.drawableToBitmap(mDrawable), getLeft(), getTop(), mPaint); }}该属性集的名字为SimpleImageView,里面只有一个名为src的整型属性。通过这个属性为自定义View添加资源id,attrs.xml代码如下:
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="SimpleImageView"> <attr name="src" format="integer"/> </declare-styleable></resources><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <com.ls.simpleimageview.SimpleImageView android:layout_width="200dp" android:layout_height="200dp" app:src="@mipmap/ic_launcher"/></LinearLayout>以上就是最简单的自定义View的实现。
新闻热点
疑难解答