1.構造方法
- 自定義屬性
ImageButtonWithText名字與自定義View名字一致,attr的名字要與其他自定義View的attr名字不同,不然會報錯
<declare-styleable name="ImageButtonWithText">
<attr name="text_img" format="string"/>
...
</declare-styleable>
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonWithText, 0, defStyle);
if (a != null) {
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.ImageButtonWithText_text_img:
text = a.getText(attr);
break;
... }
}
}
a.recycle();
- 構造方法裏獲取android內部屬性
比如想要獲取com.android.internal.R.styleable.xxx
這種屬性,不能用類似於上面的方法,但可以用getXX()的方法訪問到。
2.onMeasure()
- 用途
回調方法,比如measure裏會調用它,我們一般重寫它重新分配控件大小。
- 測量控件大小
這裏主要會用到MeasureSpec類,這個方法裏不能使用getWidth()這類方法,還有需要注意的就是最好不要寫這種代碼if(widthMode != MeasureSpec.EXACTLY)
,因爲還有其他值是不在我們熟知的三種模式裏任何一種。
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
mWidth = widthSize;
} else {}
setMeasuredDimension(mWidth, mHeight);
3.onLayout()
- 用途
回調方法,比如layout()裏會調用它,一般當自定義的View爲ViewGroup需要爲子View分配位置時重寫它。這裏淺說了下layout機制
4.獲取控件大小的幾個方法
- getWidth(),getHeight(),getLeft(),getTop()……
這一類的方法我目前理解是在onMeasure()測量之後才能獲取到值,這也就是爲什麼在onMeasure裏最好別用它的原因,它返回的值是以像素爲單位,是相對於父控件的位置,如果父控件也是根控件,我就一般用’可用’屏幕來說,不能跟整個屏幕搞混。
這裏提下View的mLeft這些屬性,他是protected,但是我們繼承了View也不能使用是因爲不在同一包裏,不過android給我們提供了上面這些方法來訪問。
- 注意這些方法與MeasureSpec.getSize()的區別
- getX()和getY()
相當於getX(0),是獲取手指觸摸的x座標,具體說是第一個手指觸摸的x座標,相對於你觸摸的控件本身而言的。裏面的數字代表第幾個手指。
- getRawX()和getRawY();
也是獲取手指觸摸的x座標,但是相對於屏幕的位置,這裏是相對整個屏幕的。
5.關於文字
FloatMath.ceil(Layout.getDesiredWidth("你的文字", "寫這些文字需要用到的Paint對象")
"Paint對象".getFontMetrics().bottom - mTextPaint.getFontMetrics().top
//FontMetrics是Paint的內部類,看他名字也大概猜到他幹嘛的
- 字體繪製
canvas.drawText(“…”,x,y,mTextPaint)是從左下角開始繪製,我試驗了下,感覺在左下角偏上一點點,所以x,y設置時要注意一下。