自訂view(一),自訂view(
轉載請註明出處:http://blog.csdn.net/ZhouLi_CSDN/article/details/46504881
自訂屬性
使用步驟:1. 通過<declare-styleable>為自訂View添加屬性2. 在xml中為相應的屬性聲明屬性值3. 在運行時(一般為建構函式)擷取屬性值4. 將擷取到的屬性值應用到View在res/values目錄下建立attr.xml檔案<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="text" format="string" /> <declare-styleable name="CustomTitleView"> <attr name="text" /> </declare-styleable> </resources>
format類型:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
xml布局檔案要引入命名空間:xmlns:custom=”http://schemas.android.com/apk/res/應用程式套件名”
可以參考:[文章]
(http://www.cnblogs.com/angeldevil/p/3479431.html)
擷取自訂屬性:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);
自訂view三個建構函式:
1. 一個參數的:java代碼建立view時調用
2. 兩個參數的:在xml建立但是沒有指定style的時候調用
3. 三個參數的:在xml建立指定style時調用
重寫onMeasure方法:
測量控制項和子控制項的寬和高並設定
MeasureSpec的三種模式:
1. EXACTLY:一般是設定了明確的值或者是MATCH_PARENT
2. AT_MOST:表示子布局限制在一個最大值內,一般為WARP_CONTENT
3. UNSPECIFIED:表示子布局想要多大就多大,很少使用
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height ; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; //直接設定值 } else { //根據內容計算大小並設定 mPaint.setTextSize(mTitleTextSize); mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds); float textWidth = mBounds.width(); int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight()); width = desired; } setMeasuredDimension(width, height); }
onLayout:
設定控制項和子控制項的位置
onDraw:
繪製控制項的內容
onDispatchDraw:
也可以繪製,但是在繪製過程中,系統先向下繪製父view的onDraw,然後子view的onDraw ; 之後在反過來向上調用子view的onDispatchDraw,然後是父view的onDispatchDraw。
所以造成的效果是: