Search code examples
javaandroid-studioandroid-layoutadmob

How do I hide a NativeAdView ad template?


How can I hide where the ad appears if there is no ad? This is the advertisement that I have. It works and there is no problem, but in the event that there is no advertisement, the template remains. I want it to disappear and appear only when an advertisement is available

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

        />

Solution

  • control the visibility from the code ,try this :

      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());