自定義控制項2 第乙個自定義view

2021-07-23 08:59:43 字數 3837 閱讀 9515

自定義乙個view, 繼承自 view, 

實現如下效果:

其實就是乙個寬高為100的藍色方塊, 左下角紅色字題 hello! (上面的hello world 是系統的 textview).

/*** 自定義乙個簡單的 view** @author gaoyuan*

*/

public

class

customview1

extends

view

// 第二個引數後面會講到

public

customview1

(context

context

,attributeset

attrs

)

@override

protected

void

ondraw

(canvas

canvas

)}

這裡面有幾個注意的點, 在注釋裡寫的都比較詳細了.

android:id

="@+id/tv_hello"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:text

="@string/hello_world"

/>

android:id

="@+id/cv_custom1"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:layout_below

="@id/tv_hello"

/>

android:id

="@+id/tv_hello2"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:text

="@string/hello_world"

android:layout_below

="@id/cv_custom1"

/>

最外層是 relativelayout, 這裡就不寫了, 注意要使用自定義view的全名作為標籤名.

上面這樣就實現了想要的效果, 但是有個問題是, 布局檔案中, 給這個控制項設定的寬高為 wrap_content, 但是實際上這個控制項的寬高卻是 match_parent, 

它下面的 textview沒有顯示出來, 

如下如所示.

這涉及到了view 的測量和繪製過程, 這裡可以先這樣理解:

我們並沒有設定它的寬高, 雖然寫了 wrap_content, 但是系統並不知道這個 "content" 到底是多大, 所以系統預設就把可以給的最大的繪製區域給它了, 從效果上來看好像是 match_parent. 但是, 如果給它設定乙個確切的寬高, 他就會按照設定的顯示:

android:id

="@+id/tv_hello"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:text

="@string/hello_world"

/>

android:id

="@+id/cv_custom1"

android:layout_width

="100dp"

android:layout_height

="100dp"

android:layout_below

="@id/tv_hello"

/>

android:id

="@+id/tv_hello2"

android:layout_width

="wrap_content"

android:layout_height

="wrap_content"

android:text

="@string/hello_world"

android:layout_below

="@id/cv_custom1"

/>

顯示效果如下:

下面先簡單的解決一下這個問題, 重寫 customview1 的 onmeasure 方法:

@overrideprotected void onmeasure(int widthmeasurespec, int heightmeasurespec)

這段話的意思是告訴父控制項我的大小是100*100, 無論怎樣都是這麼大, 此時布局檔案中的寬高都還是 wrap_content, 效果就變成下面的樣子了:

並且, 無論寬高設定的是多少, 都是100*100. 這裡就先這樣做, 後面會說 onmeasure 的意思.

來自為知筆記(wiz)

自定義控制項 自定義鐘錶

private context mcontext 畫筆 private paint mpaint 控制項的寬 private int mwidth x方向的圓心座標 private int center 鐘錶的半徑 private int mradio 圓環的寬 private int stroke...

自定義控制項(2)

自定義伺服器控制項屬性的特性 bindable 這個特性表示屬性是否可以繫結乙個有效資料來源。通常使用布林值進行設定。例如 bindable true 如果使用值true標記屬性,表示該屬性可以繫結乙個有效資料來源,且應引發該屬性的屬性更改通知。browsable 指定屬性是否應該在屬性瀏覽器中顯示...

自定義控制項《一》

view的工作流主要是指measure layout draw,即測量 布局和繪製。案例 做乙個圓形的控制項 public class circleview extends view public circleview context context,attributeset attrs publi...