天天看點

Android重寫view時onAttachedToWindow () 和 onDetachedFromWindow ()

     在重寫View的時候,會遇到這兩個方法

protected void onAttachedToWindow()

Description copied from class: View

Overrides: 

onAttachedToWindow in class View

當此view附加到窗體上時調用該方法。在這時,view有了一個用于顯示的Surface,将開始繪制。注意,此方法要保證在調用onDraw(Canvas) 之前調用,但可能在調用 onDraw(Canvas) 之前的任何時刻,包括調用 onMeasure(int, int) 之前或之後。

看得出次方法在onDraw方法之前調用,也就是view還沒有畫出來的時候,可以在此方法中去執行一些初始化的操作,google的AlarmClock動态時鐘View就是在這個方法中進行廣播的注冊,代碼如下:

@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鍵的時候也會用到

public void onAttachedToWindow() {  

this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);  

super.onAttachedToWindow();  

}  

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

protected void onDetachedFromWindow()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

onDetachedFromWindow in class AdapterView<ListAdapter>

将視圖從窗體上分離的時候調用該方法。這時視圖已經不具有可繪制部分。

onDetachedFromWindow()正好與onAttachedToWindow()的用法相對應,在destroy view的時候調用,是以可以加入取消廣播注冊等的操作,還是google的鬧鐘代碼:

    protected void onDetachedFromWindow() {  

        super.onDetachedFromWindow();  

        if (!mAttached) return;  

        mAttached = false;  

        Drawable background = getBackground();  

        if (background instanceof AnimationDrawable) {  

            ((AnimationDrawable) background).stop();  

            mContext.unregisterReceiver(mIntentReceiver);  

        mContext.getContentResolver().unregisterContentObserver(  

                mFormatChangeObserver);  

具體的用法視個人的需求而定了,自己控制重寫就好了。

    本文轉自 一點點征服   部落格園部落格,原文連結:http://www.cnblogs.com/ldq2016/p/6867895.html,如需轉載請自行聯系原作者

繼續閱讀