Native ads - adiant/android-sdk-example GitHub Wiki
Native ads
The Ads SDK supports displaying native ads with your custom layout in a ListView or GridView.
Create a layout for native ads, e.g. list_item_native_ad.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingLeft="@dimen/list_item_horizontal_margin"
android:paddingRight="@dimen/list_item_horizontal_margin"
android:paddingTop="@dimen/list_item_vertical_margin"
android:paddingBottom="@dimen/list_item_vertical_margin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="@dimen/list_item_horizontal_margin"
android:id="@+id/imageView"
android:layout_centerVertical="true"
android:contentDescription="@string/ads_description" />
<TextView
android:text="@string/interstitial_intro"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/imageView"
android:id="@+id/textViewTitle" />
<TextView
android:text="@string/interstitial_intro"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textViewTitle"
android:layout_toRightOf="@+id/imageView"
android:id="@+id/textViewDescription" />
</RelativeLayout>
- Create a NativeAdFactory instance as early as possible, and preload ads to show in the list.
- Be sure to use your ad unit ID with the NativeAdFactory.
- Wrap your list adapter within a NativeAdAdapter.
- Create a NativeAdInflater that will create the view for each native ad.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create ad factory
NativeAdFactory adFactory = new NativeAdFactory(getActivity(), "13325-2514722925", new NativeAdArbiter());
// estimate total items shown
adFactory.init(10);
ListAdapter adapter;
// setup your adapter ...
// create a view binder that sets the resource IDs for each
ViewBinder binder = new ViewBinder.Builder()
.setImageId(R.id.imageView)
.setTitleId(R.id.textViewTitle)
.setDescriptionId(R.id.textViewDescription)
.setDisplayNameId(R.id.textViewDisplayName)
.create();
// create ad inflater with the resource ID for your native ad layout
NativeAdInflater adInflater = new NativeAdInflater(getActivity(), binder, R.layout.list_item_native_ad);
// wrap adapter inside adapter that inserts native ads
adapterWithAds = new NativeAdAdapter(adapter, adInflater, adFactory);
// use the adapter
setListAdapter(adapterWithAds);
}
Add a hook to clean-up resources in the the fragment's onDestroy() method. This is necessary only for Android 2.3.3 (API level 10) and lower.
@Override
public void onDestroy() {
if (adapterWithAds != null) {
adapterWithAds.destroy();
}
super.onDestroy();
}