代码之家  ›  专栏  ›  技术社区  ›  Aness

java.lang.IllegalStateException:OnGetLayoutFlater()在片段附加到片段管理器之前无法执行

  •  0
  • Aness  · 技术社区  · 5 年前

    嗨,我想在我的Android应用程序中实现本地广告,所以我有 this code ,您可以在Github中检查源代码。

    它有时会在Logcat中触发此错误:

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.august_themes.free_fast_stock_inventory_manager, PID: 3234
    java.lang.IllegalStateException: onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager.
        at androidx.fragment.app.Fragment.getLayoutInflater(Fragment.java:1503)
        at androidx.fragment.app.Fragment.onGetLayoutInflater(Fragment.java:1452)
        at androidx.fragment.app.Fragment.performGetLayoutInflater(Fragment.java:1484)
    

    执行此代码时出错:

      private void refreshAd() {
        refresh.setEnabled(false);
    
        AdLoader.Builder builder = new AdLoader.Builder(getContext(), getResources().getString(R.string.AdmobNativeAdsID));
    
        builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
            // OnUnifiedNativeAdLoadedListener implementation.
            @Override
            public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
                // You must call destroy on old ads when you are done with them,
                // otherwise you will have a memory leak.
                if (nativeAd != null) {
                    nativeAd.destroy();
                }
                nativeAd = unifiedNativeAd;
                FrameLayout frameLayout =
                        v.findViewById(R.id.nativeads_adplaceholder);
                UnifiedNativeAdView adView = (UnifiedNativeAdView) getLayoutInflater()
                        .inflate(R.layout.ad_unified, null);
                populateUnifiedNativeAdView(unifiedNativeAd, adView);
                frameLayout.removeAllViews();
                frameLayout.addView(adView);
            }
    
        });
    

    我们在讨论这一行代码

      UnifiedNativeAdView adView = (UnifiedNativeAdView) getLayoutInflater().inflate(R.layout.ad_unified, null);
    

    在调用此函数getLayoutFlater()之前,我是否可以测试类似于implementation condition的东西来确保片段附加到片段管理器?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Nima Ganji    5 年前

    你的问题根据 Android Developers 碎片有 .isAdded() 希望有帮助。