一,view的繪制過程
- onMeasure():測量view的寬度和高度,根據(jù)自身的MeasureSpec和具體背景設(shè)置而定,自身view的MeasureSpec由自身的LayoutParams和父類的MeasureSpec決定。
- onLayout():計(jì)算view的位置,left,right,top,bottom,四個(gè)點(diǎn)的位置。
- onDraw():在屏幕上渲染view。
二,自定義view的總結(jié)
- 繼承原生的view,實(shí)現(xiàn)ondraw()方法,設(shè)計(jì)規(guī)則特殊的view,這種方式,需要實(shí)現(xiàn)wrap_content和padding。
- 繼承原生的viewgroup,設(shè)計(jì)新的布局方式,這種方式,需要實(shí)現(xiàn)測量onMeasure和布局onLayout。
- 繼承特定的view,如textview,不需要實(shí)現(xiàn)wrap_content和padding,用來擴(kuò)展view的功能。
- 繼承特定的viewgroup,如LinearLayout,不用實(shí)現(xiàn)測量和布局的方法,用來設(shè)計(jì)基于此布局的新的布局。
三,自定義view的過程
- 設(shè)計(jì)繼承view的類,至少實(shí)現(xiàn)兩個(gè)構(gòu)造方法:
//如果View是在Java代碼里面new的,則調(diào)用第一個(gè)構(gòu)造函數(shù)
public CustomView(Context context)
{
super(context);
}
// 如果View是在.xml里聲明的,則調(diào)用第二個(gè)構(gòu)造函數(shù)
// 自定義屬性是從AttributeSet參數(shù)傳進(jìn)來的
public CustomView(Context context,AttributeSet attrs)
{
super(context, attrs);
}
- 自定義屬性的設(shè)計(jì):有時(shí)候需要設(shè)計(jì)除了系統(tǒng)給定之外的其它屬性,需要以下幾步:
- 在資源文件中,增加對于自定義view的自定義屬性的說明:
<declare-styleable name="CustomView">
<attr name="custom_attr" format="color|drawable">
</declare-styleable>
- 在具體使用CustomView的布局文件中加上這句代碼,其中‘a(chǎn)pp’要和真正使用一致:**
xmlns:app="http://schems.android.com/apk/res-auto"
- 在布局設(shè)置CustomView的自定義屬性:
<CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:custom_attr="#fff">
</CustomView>
- 在自定義View的構(gòu)造函數(shù)中使用自定義屬性:
public CustomView(Context context,AttributeSet attrs)
{
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(arrs,R.styleable.CustomView);
mcolor = ta.getColor(R.styleable.CustomView_custom_attr,Color.RED);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。