如何隐藏 NativeAdView 广告模板?

How do I hide a NativeAdView ad template?

如果没有广告,如何隐藏广告出现的位置? 这是我的广告。它可以工作并且没有问题,但是如果没有广告,模板仍然存在。我想让它消失,只在有广告时出现

enter image description here

NativeAdView

 AdLoader adLoader = new AdLoader.Builder(this, getString(R.string.admob_native_id4)) 
            .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
                @Override
                public void onNativeAdLoaded(NativeAd nativeAd) {
                    NativeTemplateStyle styles = new
                            NativeTemplateStyle.Builder().build();
                    TemplateView template = findViewById(R.id.native_ad_1); 
                    template.setStyles(styles);
                    template.setNativeAd(nativeAd);
                }
            })
            .build();

    adLoader.loadAd(new AdRequest.Builder().build());

template

    <com.google.android.ads.nativetemplates.TemplateView
        android:id="@+id/native_ad_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:gnt_template_type="@layout/gnt_medium_template_view"

        android:visibility="gone"    //When I add this, the template disappears, but the ad does not appear

        />

通过代码控制可见性,试试这个:

  AdLoader adLoader = new AdLoader.Builder(this, getString(R.string.admob_native_id4)) 
        .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
            @Override
            public void onNativeAdLoaded(NativeAd nativeAd) {
                NativeTemplateStyle styles = new
                        NativeTemplateStyle.Builder().build();
                TemplateView template = findViewById(R.id.native_ad_1); 
                template.setStyles(styles);
                
                //// if the ad is not null make the template visible otherwise hide it
                if (nativeAd != null){
                    template.setNativeAd(nativeAd);
                    template.setVisibility(View.VISIBLE);
                }else{
                    template.setVisibility(View.GONE);
                }

            }
        }).build();

  adLoader.loadAd(new AdRequest.Builder().build());