雖然Android已經(jīng)自帶了很多強(qiáng)大的控件,但是仍然不能滿足開發(fā)的需求,自定義view已經(jīng)成為了開發(fā)者必須要掌握的最重要的技能之一。
首先介紹主要步驟: 1、繼承自View創(chuàng)建自定義控件; 2、如有需要自定義View屬性,就在values/attrs.xml中定義屬性集; 3、在xml中引入命名控件,設(shè)置屬性; 4、在代碼中讀取xml中的屬性,初始化視圖; 5、測(cè)量視圖大小; 6、繪制視圖內(nèi)容。
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); //根據(jù)屬性初始化 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); //根據(jù)圖片id獲取drawable對(duì)象 mDrawable = array.getDrawable(R.styleable.SimpleImageView_src); //測(cè)量Drawable對(duì)象的寬高 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,里面只有一個(gè)名為src的整型屬性。通過(guò)這個(gè)屬性為自定義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="@m以上就是最簡(jiǎn)單的自定義View的實(shí)現(xiàn)。新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注