国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android自定義view代碼步驟

2019-11-09 18:01:36
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

雖然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)。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 邛崃市| 海宁市| 宣武区| 德兴市| 天全县| 兴和县| 密云县| 那曲县| 湛江市| 柳林县| 日土县| 漯河市| 达尔| 轮台县| 淳安县| 荃湾区| 永定县| 宝兴县| 南丹县| 乾安县| 德阳市| 大关县| 车险| 彰化市| 温宿县| 泸定县| 汉寿县| 五莲县| 西城区| 宝兴县| 花莲县| 常熟市| 桦南县| 江达县| 阳原县| 保山市| 霍林郭勒市| 巴林左旗| 上犹县| 昭觉县| 闻喜县|