在重寫View的時候,會遇到這兩個方法
protected void onAttachedToWindow()
Description copied from class: View
This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before View.onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after View.onMeasure(int, int).
Overrides:
onAttachedToWindow in class View
當此view附加到窗體上時調用該方法。在這時,view有了一個用於顯示的Surface,將開始繪制。注意,此方法要保證在調用onDraw(Canvas) 之前調用,但可能在調用 onDraw(Canvas) 之前的任何時刻,包括調用 onMeasure(int, int) 之前或之後。
看得出次方法在onDraw方法之前調用,也就是view還沒有畫出來的時候,可以在此方法中去執行一些初始化的操作,google的AlarmClock動態時鐘View就是在這個方法中進行廣播的注冊,代碼如下:
[java]
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (Log.LOGV) Log.v("onAttachedToWindow " + this);
if (mAttached) return;
mAttached = true;
if (mAnimate) {
setBackgroundResource(R.drawable.animate_circle);
/* Start the animation (looped playback by default). */
((AnimationDrawable) getBackground()).start();
}
if (mLive) {
/* monitor time ticks, time changed, timezone */
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
mContext.registerReceiver(mIntentReceiver, filter, null, mHandler);
}
/* monitor 12/24-hour display preference */
mFormatChangeObserver = new FormatChangeObserver();
mContext.getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
updateTime();
}
另外在屏蔽Home鍵的時候也會用到
[java]
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
protected void onDetachedFromWindow()
Description copied from class: View
This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
Overrides:
onDetachedFromWindow in class AdapterView<ListAdapter>
將視圖從窗體上分離的時候調用該方法。這時視圖已經不具有可繪制部分。
onDetachedFromWindow()正好與onAttachedToWindow()的用法相對應,在destroy view的時候調用,所以可以加入取消廣播注冊等的操作,還是google的鬧鐘代碼:
[java]
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (!mAttached) return;
mAttached = false;
Drawable background = getBackground();
if (background instanceof AnimationDrawable) {
((AnimationDrawable) background).stop();
} www.2cto.com
if (mLive) {
mContext.unregisterReceiver(mIntentReceiver);
}
mContext.getContentResolver().unregisterContentObserver(
mFormatChangeObserver);
}
具體的用法視個人的需求而定了,自己控制重寫就好了。