Admob Native ads in Android – Admob Ads v-20.1.0
Admob Native Ads are One of the Best Ad Formats of Admob. They are Easily Customized. And they can be integrated into your app Content and they Display ads that match your Content. So Users who use your app show interest in Admob Native Ads So you can generate more Revenue.
I Personally Suggest you Use Admob Native Ads in your App. So you Can Earn More Revenue.
Now Let’s See about Native Ads.
Table of Contents
Native Ads:
Native ads are ad assets that are presented to users via UI components that are native to the platform. They’re shown using the same types of views with which you’re already building your layouts, and can be formatted to match the visual design of the user experience in which they live. In coding terms, this means that when a native ad loads, your app receives a NativeAd object that contains its assets, and the app (rather than the Google Mobile Ads SDK) is then responsible for displaying them.
Ok, I think Now you Got what are Native Ads. So Now Let’s Go to the Coding Part.
Check Our Interstitial Ads Tutorial
First Integrate Admob SDK into your App.
Now Create the ad_unified.xml file, the Layout of Our Native Ad.
ad_unified.xml
<?xml version="1.0" encoding="utf-8"?> <com.google.android.gms.ads.nativead.NativeAdView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:background="#FFFFFF" android:minHeight="50dp" android:orientation="vertical"> <TextView style="@style/Theme.AdmobSampleApp.AdAttribution"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="3dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/ad_app_icon" android:layout_width="40dp" android:layout_height="40dp" android:adjustViewBounds="true" android:paddingBottom="5dp" android:paddingEnd="5dp" android:paddingRight="5dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/ad_headline" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#0000FF" android:textSize="16sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/ad_advertiser" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="bottom" android:textSize="14sp" android:textStyle="bold"/> <RatingBar android:id="@+id/ad_stars" style="?android:attr/ratingBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:isIndicator="true" android:numStars="5" android:stepSize="0.5" /> </LinearLayout> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/ad_body" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:layout_marginEnd="20dp" android:textSize="12sp" /> <com.google.android.gms.ads.nativead.MediaView android:id="@+id/ad_media" android:layout_gravity="center_horizontal" android:layout_width="250dp" android:layout_height="175dp" android:layout_marginTop="5dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:orientation="horizontal" android:paddingBottom="10dp" android:paddingTop="10dp"> <TextView android:id="@+id/ad_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="5dp" android:paddingStart="5dp" android:paddingRight="5dp" android:paddingEnd="5dp" android:textSize="12sp" /> <TextView android:id="@+id/ad_store" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="5dp" android:paddingStart="5dp" android:paddingRight="5dp" android:paddingEnd="5dp" android:textSize="12sp" /> <Button android:id="@+id/ad_call_to_action" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textSize="12sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </com.google.android.gms.ads.nativead.NativeAdView>
In your themes.xml create the style for Native Ad with the below code.
<style name="Theme.AdmobSampleApp.AdAttribution"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_gravity">left</item> <item name="android:textColor">#FFFFFF</item> <item name="android:textSize">12sp</item> <item name="android:text">@string/ad_attribution</item> <item name="android:background">#FFCC66</item> <item name="android:width">15dp</item> <item name="android:height">15dp</item> </style>
Now Create a FrameLayout in activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <FrameLayout android:id="@+id/fl_adplaceholder" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" /> <CheckBox android:id="@+id/cb_start_muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Start video ads muted" /> <Button android:id="@+id/btn_refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="16dp" android:layout_marginTop="16dp" android:text="Refresh Ad" /> <TextView android:text="Video status: " android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/activity_horizontal_margin" android:layout_marginRight="@dimen/activity_horizontal_margin" android:id="@+id/tv_video_status" android:textAppearance="@style/TextAppearance.AppCompat.Medium" /> </LinearLayout> <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" ads:adSize="BANNER" ads:adUnitId="ca-app-pub-3940256099942544/6300978111"> </com.google.android.gms.ads.AdView> </RelativeLayout>
Note: The above Layout also contains Banner Ad implementation. if you don’t need Banner Ad just remove Banner Ad Code.
Now Let’s See the Full Code in MainActivity.java for Native Ads
MainActivity.java
package com.example.admobsampleapp; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.VideoController; import com.google.android.gms.ads.VideoOptions; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.ads.nativead.MediaView; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAdOptions; import com.google.android.gms.ads.nativead.NativeAdView; public class MainActivity extends AppCompatActivity { private AdView mAdView; private static final String TAG = "MainActivity"; private static final String ADMOB_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110"; private Button refresh; private CheckBox startVideoAdsMuted; private TextView videoStatus; private NativeAd nativeAd; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); //Start of Admob Banner Code mAdView = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); //End of Admob Banner Code refresh = findViewById(R.id.btn_refresh); startVideoAdsMuted = findViewById(R.id.cb_start_muted); videoStatus = findViewById(R.id.tv_video_status); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { refreshAd(); } }); refreshAd(); } private void populateNativeAdView(NativeAd nativeAd, NativeAdView adView) { // Set the media view. adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media)); // Set other ad assets. adView.setHeadlineView(adView.findViewById(R.id.ad_headline)); adView.setBodyView(adView.findViewById(R.id.ad_body)); adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action)); adView.setIconView(adView.findViewById(R.id.ad_app_icon)); adView.setPriceView(adView.findViewById(R.id.ad_price)); adView.setStarRatingView(adView.findViewById(R.id.ad_stars)); adView.setStoreView(adView.findViewById(R.id.ad_store)); adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser)); // The headline and mediaContent are guaranteed to be in every NativeAd. ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline()); adView.getMediaView().setMediaContent(nativeAd.getMediaContent()); // These assets aren't guaranteed to be in every NativeAd, so it's important to // check before trying to display them. if (nativeAd.getBody() == null) { adView.getBodyView().setVisibility(View.INVISIBLE); } else { adView.getBodyView().setVisibility(View.VISIBLE); ((TextView) adView.getBodyView()).setText(nativeAd.getBody()); } if (nativeAd.getCallToAction() == null) { adView.getCallToActionView().setVisibility(View.INVISIBLE); } else { adView.getCallToActionView().setVisibility(View.VISIBLE); ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction()); } if (nativeAd.getIcon() == null) { adView.getIconView().setVisibility(View.GONE); } else { ((ImageView) adView.getIconView()).setImageDrawable( nativeAd.getIcon().getDrawable()); adView.getIconView().setVisibility(View.VISIBLE); } if (nativeAd.getPrice() == null) { adView.getPriceView().setVisibility(View.INVISIBLE); } else { adView.getPriceView().setVisibility(View.VISIBLE); ((TextView) adView.getPriceView()).setText(nativeAd.getPrice()); } if (nativeAd.getStore() == null) { adView.getStoreView().setVisibility(View.INVISIBLE); } else { adView.getStoreView().setVisibility(View.VISIBLE); ((TextView) adView.getStoreView()).setText(nativeAd.getStore()); } if (nativeAd.getStarRating() == null) { adView.getStarRatingView().setVisibility(View.INVISIBLE); } else { ((RatingBar) adView.getStarRatingView()) .setRating(nativeAd.getStarRating().floatValue()); adView.getStarRatingView().setVisibility(View.VISIBLE); } if (nativeAd.getAdvertiser() == null) { adView.getAdvertiserView().setVisibility(View.INVISIBLE); } else { ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser()); adView.getAdvertiserView().setVisibility(View.VISIBLE); } // This method tells the Google Mobile Ads SDK that you have finished populating your // native ad view with this native ad. adView.setNativeAd(nativeAd); // Get the video controller for the ad. One will always be provided, even if the ad doesn't // have a video asset. VideoController vc = nativeAd.getMediaContent().getVideoController(); // Updates the UI to say whether or not this ad has a video asset. if (vc.hasVideoContent()) { // Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The // VideoController will call methods on this object when events occur in the video // lifecycle. vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() { @Override public void onVideoEnd() { // Publishers should allow native ads to complete video playback before // refreshing or replacing them with another ad in the same UI location. refresh.setEnabled(true); videoStatus.setText("Video status: Video playback has ended."); super.onVideoEnd(); } }); } else { videoStatus.setText("Video status: Ad does not contain a video asset."); refresh.setEnabled(true); } } /** * Creates a request for a new native ad based on the boolean parameters and calls the * corresponding "populate" method when one is successfully returned. * */ private void refreshAd() { refresh.setEnabled(false); AdLoader.Builder builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID); builder.forNativeAd( new NativeAd.OnNativeAdLoadedListener() { // OnLoadedListener implementation. @Override public void onNativeAdLoaded(NativeAd nativeAd) { // If this callback occurs after the activity is destroyed, you must call // destroy and return or you may get a memory leak. boolean isDestroyed = false; refresh.setEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { isDestroyed = isDestroyed(); } if (isDestroyed || isFinishing() || isChangingConfigurations()) { nativeAd.destroy(); return; } // You must call destroy on old ads when you are done with them, // otherwise you will have a memory leak. if (MainActivity.this.nativeAd != null) { MainActivity.this.nativeAd.destroy(); } MainActivity.this.nativeAd = nativeAd; FrameLayout frameLayout = findViewById(R.id.fl_adplaceholder); NativeAdView adView = (NativeAdView) getLayoutInflater().inflate(R.layout.ad_unified, null); populateNativeAdView(nativeAd, adView); frameLayout.removeAllViews(); frameLayout.addView(adView); } }); VideoOptions videoOptions = new VideoOptions.Builder().setStartMuted(startVideoAdsMuted.isChecked()).build(); NativeAdOptions adOptions = new NativeAdOptions.Builder().setVideoOptions(videoOptions).build(); builder.withNativeAdOptions(adOptions); AdLoader adLoader = builder .withAdListener( new AdListener() { @Override public void onAdFailedToLoad(LoadAdError loadAdError) { refresh.setEnabled(true); String error = String.format( "domain: %s, code: %d, message: %s", loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage()); Toast.makeText( MainActivity.this, "Failed to load native ad with error " + error, Toast.LENGTH_SHORT) .show(); } }) .build(); adLoader.loadAd(new AdRequest.Builder().build()); videoStatus.setText(""); } @Override protected void onDestroy() { if (nativeAd != null) { nativeAd.destroy(); } super.onDestroy(); } }
That’s it, guys. I hope You learned how to Integrate Admob Native Ads in Android. See you in the next tutorial guys. If you have any doubts please contact me or you can ask your question in the comment section below.
Thank you.