android窗口泄漏,isInEditMode解決可視化編輯器無法識別自定義控件的問題


android窗口泄漏

在做項目是遇到這個錯誤:google:WindowManager: Activity has leaked window.

產 生原因:我們知道Android的每一個Activity都有個WindowManager窗體管理器,同樣構建在某個Activity之上的對話框、 PopupWindow也有相應的WindowManager窗體管理器。因為對話框、PopupWindow不能脫離Activity而單獨存在着,所 以當某個Dialog或者某個PopupWindow正在顯示的時候我們去finish()了承載該Dialog或PopupWindow的 Activity時,就會拋WindowLeaked異常了,因為這個Dialog或PopupWindow的WindowManager已經沒有誰可以 附屬了,所以它的窗體管理器已經泄漏了。

Activity中create一個Dialog,若你先關閉Dialog再關閉Activity就是正常的,若你先關閉Activity再關閉Dialog就會報錯這個android.view.WindowLeaked錯誤了。

分析這個原因是:Dialog是基於Activity而創建的new Dialog(this);this就是Activity。 Activtity先finish,那Dialog就沒得依附了,所以就會報android.view.WindowLeaked。

還有如果是WindowManager通過addView方法加上去的view,在activity退出之前一定要調用removeView,否則也會產生窗口泄漏。

使用isInEditMode解決可視化編輯器無法識別自定義控件的問題

isInEditMode:

Indicates whether this View is currentlyin edit mode. A View is usually in edit mode when displayed within a developertool. For instance, if this View is being drawn by a visual user interfacebuilder, this method should return true. Subclasses should check the returnvalue of this method to provide different behaviors if their normal behaviormight interfere with the host environment. For instance: the class spawns athread in its constructor, the drawing code relies on device-specific features,etc. This method is usually checked in the drawing code of custom widgets.

如果在自定義控件的構造函數或者其他繪制相關地方使用系統依賴的代碼,會導致可視化編輯器無法報錯並提示:Use View.isInEditMode() in your custom views to skip code when shownin Eclipse

比如:

public class LockRelativeLayout extends RelativeLayout {    private Handler mainHandler = null; //與主Activity通信的Handler對象    public LockRelativeLayout(Context context, AttributeSet attrs) {        super(context, attrs, 0);        mContext = context;        if (isInEditMode()) { return; }        mainHandler = ((SPActivity)mContext).getMHandler();    }}

如果不加上if(isInEditMode()) { return; },標紅處代碼會導致可視化編輯報錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM