11package com .d4rk .androidtutorials .java .ads .managers ;
22
33import android .content .Context ;
4+ import android .util .Log ;
45import android .view .LayoutInflater ;
56import android .view .View ;
67import android .view .ViewGroup ;
78import android .widget .Button ;
89import android .widget .ImageView ;
910import android .widget .TextView ;
1011
11- import androidx .annotation .NonNull ;
1212import androidx .annotation .LayoutRes ;
13+ import androidx .annotation .NonNull ;
1314
1415import com .d4rk .androidtutorials .java .R ;
16+ import com .google .android .gms .ads .AdListener ;
1517import com .google .android .gms .ads .AdLoader ;
1618import com .google .android .gms .ads .AdRequest ;
19+ import com .google .android .gms .ads .LoadAdError ;
1720import com .google .android .gms .ads .nativead .MediaView ;
1821import com .google .android .gms .ads .nativead .NativeAd ;
1922import com .google .android .gms .ads .nativead .NativeAdView ;
2326 */
2427public class NativeAdLoader {
2528
29+ private static final String TAG = "NativeAdLoader" ;
30+ 2631 public static void load (@ NonNull Context context , @ NonNull ViewGroup container ) {
27- load (context , container , R .layout .large_home_banner_native_ad );
32+ load (context , container , R .layout .large_home_banner_native_ad , null );
2833 }
2934
3035 public static void load (@ NonNull Context context , @ NonNull ViewGroup container , @ LayoutRes int layoutRes ) {
31- AdLoader adLoader = new AdLoader .Builder (context , context .getString (R .string .native_ad_banner_unit_id ))
36+ load (context , container , layoutRes , null );
37+ }
38+ 39+ public static void load (@ NonNull Context context ,
40+ @ NonNull ViewGroup container ,
41+ @ LayoutRes int layoutRes ,
42+ @ androidx .annotation .Nullable AdListener listener ) {
43+ AdLoader .Builder builder = new AdLoader .Builder (context , context .getString (R .string .native_ad_banner_unit_id ))
3244 .forNativeAd (nativeAd -> {
3345 LayoutInflater inflater = LayoutInflater .from (context );
3446 NativeAdView adView = (NativeAdView ) inflater .inflate (layoutRes , container , false );
@@ -41,8 +53,19 @@ public static void load(@NonNull Context context, @NonNull ViewGroup container,
4153 populateNativeAdView (nativeAd , adView );
4254 container .removeAllViews ();
4355 container .addView (adView );
44- })
45- .build ();
56+ container .requestLayout ();
57+ });
58+ 59+ builder .withAdListener (listener != null ? listener : new AdListener () {
60+ @ Override
61+ public void onAdFailedToLoad (@ NonNull LoadAdError loadAdError ) {
62+ Log .w (TAG , "Failed to load native ad: " + loadAdError .getMessage ());
63+ container .removeAllViews ();
64+ container .setVisibility (View .GONE );
65+ }
66+ });
67+ 68+ AdLoader adLoader = builder .build ();
4669 adLoader .loadAd (new AdRequest .Builder ().build ());
4770 }
4871
0 commit comments