android開發BadTokenException: Unable to add window -- token null is not valid; is your activity running?比較好的解決方法


BadTokenException: Unable to add window -- token null is not valid; is your activity running?比較好的解決方法

  1. 具體崩潰信息:

    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:1165)

  2. 崩潰原因是:

    調用了popupWindow.showAtLocation,比如popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0),

    而如果這個anchorView還沒有添加到Activity,或者Activity剛好關閉了,比如剛好手機來電話了等等都會偶爾受影響,

    此時調用popupWindow.showAtLocation方法就會出現BadTokenException異常,因為anchorView的windowToken為空。

    說白了崩潰原因就是因為anchorView的windowToken為空。

    復現案例:在Activity的onCreate方法里調用popupWindow.showAtLocation就會出現。。。

  3. 比較好的解決方法

    private fun showPopWindow(anchorView: View) {
            val popupWindow = PopupWindow(this)
            popupWindow.contentView =...
            if (anchorView.windowToken != null){//判斷一下如果windowToken不為空才顯示,不然延遲200ms再試試
                popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0)
            }else{
                Handler(Looper.getMainLooper()).postDelayed({
                    if (anchorView.windowToken != null){//延遲200ms后再判斷保證windowToken不為空才顯示
                        popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0)
                    }
                },200)
            }
        }
    


免責聲明!

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



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