實習入職第二天:onAttachedToWindow () 和 onDetachedFromWindow ()
在重寫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就是在這個方法中進行廣播的註冊,程式碼如下:
- @Override
-
protectedvoid 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鍵的時候也會用到
- publicvoid 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的鬧鐘程式碼:
- @Override
- protectedvoid onDetachedFromWindow() {
- super.onDetachedFromWindow();
- if (!mAttached) return;
- mAttached = false;
- Drawable background = getBackground();
- if (background instanceof AnimationDrawable) {
- ((AnimationDrawable) background).stop();
- }
- if (mLive) {
- mContext.unregisterReceiver(mIntentReceiver);
- }
- mContext.getContentResolver().unregisterContentObserver(
- mFormatChangeObserver);
- }
具體的用法視個人的需求而定了,自己控制重寫就好了。