安卓自定義view繪製尺寸

2021-08-02 12:13:50 字數 2251 閱讀 7959

我們知道view在螢幕上顯示出來要先經過measure和layout. 在呼叫onmeasure(int widthspec, int heightspec)方法時,要涉及到measurespec的使用,measurespec有3種模式分別是unspecified, exactly和at_most, 那麼這些模式和我們平時設定的layout引數fill_parent, wrap_content有什麼關係呢。經過**測試就知道,當我們設定width或height為fill_parent時,容器在布局時呼叫子 view的measure方法傳入的模式是exactly,因為子view會佔據剩餘容器的空間,所以它大小是確定的。而當設定為 wrap_content時,容器傳進去的是at_most, 表示子view的大小最多是多少,這樣子view會根據這個上限來設定自己的尺寸。當子view的大小設定為精確值時,容器傳入的是exactly, 而measurespec的unspecified模式目前還沒有發現在什麼情況下使用。

measurespec它常用的三個函式:

1.static int getmode(int measurespec):根據提供的測量值(格式)提取模式(上述三個模式之一)

2.static int getsize(int measurespec):根據提供的測量值(格式)提取大小值(這個大小也就是我們通常所說的大小)

3.static int makemeasurespec(int size,int mode):根據提供的大小值和模式建立乙個測量值(格式)

這個類的使用呢,通常在view元件的onmeasure方法裡面呼叫但也有少數例外,看看幾個例子:

a.首先乙個我們常用到的乙個有用的函式,view.resolvesize(int size,int measurespec)
public static int resolvesize(int size, int measurespec)

return result;}

上面既然要用到measurespec值,那自然表示這個函式通常是在onmeasure方法裡面呼叫的。簡單說一下,這個方法的主要作用就是根據你提供的大小和模式,返回你想要的大小值,這個裡面根據傳入模式的不同來做相應的處理。

再看看measurespec.makemeasurespec方法,實際上這個方法很簡單

public static int makemeasurespec(int size, int mode)

這樣大家不難理解size跟measurespec區別了。看看它的使用吧,listview.measureitem(view child)

private void measureitem(view child)

int childwidthspec = viewgroup.getchildmeasurespec(mwidthmeasurespec,

mlistpadding.left + mlistpadding.right, p.width);

int lpheight = p.height;

int childheightspec;

if (lpheight > 0)

else

child.measure(childwidthspec, childheightspec);}

measurespec方法通常在viewgroup中用到,它可以根據模式(measurespec裡面的三個)可以調節子元素的大小。

注意,使用exactly和at_most通常是一樣的效 果,如果你要區別他們,那麼你就要使用上面的函式view.resolvesize(int size,int measurespec)返回乙個size值,然後使用你的view呼叫setmeasureddimension(int,int)函式。

protected final void setmeasureddimension(int measuredwidth, int measuredheight)

mmeasuredwidth = measuredwidth;

mmeasuredheight = measuredheight;

mprivateflags |= measured_dimension_set;

然後你呼叫view.getmeasuredwidth,view.getmeasuredheigth 返回的就是上面函式裡的mmeasuredwidth,mmeasuredheight的值。

我們可以通過重寫onmeasure來自定義測量過程。如果view沒有重寫onmeasure方法,缺省會直接呼叫getdefaultsize來獲得view的寬高。

安卓自定義繪製View中遇到的問題

第乙個建構函式 public mycustomview context context 第二個建構函式 public mycustomview context context,attributeset attrs 第三個建構函式 public mycustomview context context...

安卓自定義View 座標系篇

由於移動裝置一般定義螢幕左上角為座標原點,向右為x軸增大方向,向下為y軸增大方向,所以在在手機螢幕上的座標系與數學中常見的座標繫在y軸的方向上是相反的。如下圖 下圖中的 是對應的 實際螢幕上的預設座標系如下 其中棕色部分為手機螢幕 注意 view的座標系是相對于父控制項而言的 gettop 獲取子v...

安卓自定義View基礎 座標系

由於移動裝置一般定義螢幕左上角為座標原點,向右為x軸增大方向,向下為y軸增大方向,所以在手機螢幕上的座標系與數學中常見的座標系是稍微有點差別的,詳情如下 ps 其中的 a 是對應的,注意y軸方向!實際螢幕上的預設座標系如下 ps 假設其中棕色部分為手機螢幕 注意 view的座標系統是相對于父控制項而...