標籤:
Android遊戲開發之旅 View類詳解
自訂 View的常用方法:
onFinishInflate() 當View中所有的子控制項 均被映射成xml後觸發
onMeasure(int, int) 確定所有子項目的大小
onLayout(boolean, int, int, int, int) 當View分配所有的子項目的大小和位置時觸發
onSizeChanged(int, int, int, int) 當view的大小發生變化時觸發
onDraw(Canvas) view渲染內容的細節
onKeyDown(int, KeyEvent) 有按鍵按下後觸發
onKeyUp(int, KeyEvent) 有按鍵按下後彈起時觸發
onTrackballEvent(MotionEvent) 軌跡球事件
onTouchEvent(MotionEvent) 觸屏事件
onFocusChanged(boolean, int, Rect) 當View擷取 或失去焦點時觸發
onWindowFocusChanged(boolean) 當視窗包含的view擷取或失去焦點時觸發
onAttachedToWindow() 當view被附著到一個視窗時觸發
onDetachedFromWindow() 當view離開附著的視窗時觸發,Android123提示該方法和 onAttachedToWindow() 是相反的。
onWindowVisibilityChanged(int) 當視窗中包含的可見的view發生變化時觸發
以上是View實現的一些基本介面的回調方法,一般我們需要處理畫布的顯示時,重寫onDraw(Canvas)用的的是最多的:
view plaincopy to clipboardprint
@Override
protected void onDraw(Canvas canvas) {
//這裡我們直接使用canvas對象處理當前的畫布,比如說使用Paint來選擇要填充的顏色
Paint paintBackground = new Paint();
paintBackground.setColor(getResources().getColor(R.color.xxx)); //從Res中找到名為xxx的color顏色定義
canvas.drawRect(0, 0, getWidth(), getHeight(), paintBackground); //設定當前畫布的背景顏色為paintBackground中定義的顏色,以0,0作為為起點,以當前畫布的寬度和高度為重點即整塊畫布來填充,具體的請查看Android123未來講到的Canvas和Paint,在Canvas中我們可以實現畫路徑,圖形,地區,線。而Paint作為繪畫方式的對象可以設定顏色,大小,甚至字型的類型等等。
}
當然還有就是處理視窗還原狀態問題(一般用於橫豎屏切換),除了在Activity中可以調用外,開發遊戲時我們盡量在View中使用類似
view plaincopy to clipboardprint
@Override
protected Parcelable onSaveInstanceState() {
Parcelable p = super.onSaveInstanceState();
Bundle bundle = new Bundle();
bundle.putInt("x", pX);
bundle.putInt("y", pY);
bundle.putParcelable("android123_state", p);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
dosomething(bundle.getInt("x"), bundle.getInt("y")); //擷取剛才儲存的x和y資訊
super.onRestoreInstanceState(bundle.getParcelable("android123_state"));
return;
}
出自: doc-view-5324.html
Android遊戲開發之旅 View類詳解