Embedding ads within Recyclerview
In your adapter, you first need to override getItemViewType, for example:
@Override
public int getItemViewType(int position)
{
if (position % 5 == 0)
return AD_TYPE;
return CONTENT_TYPE;
}
Then in onCreateViewHolder, inflate a different view according to the type. Something like this:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
{
View v = null;
if (viewType == AD_TYPE)
{
v = new AdView(activity, AdSize.BANNER, ADMOB_ID);
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT,height);
v.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder().build();
if (adRequest != null && v != null){
v.loadAd(adRequest);
}
}
else
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_layout, viewGroup, false);
RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(v);
return viewHolder;
}
Ads in recyclerview
Fundamentally, a RecyclerView
is used to display a List
to the user. Use this to guide your implementation.
Currently, you have two lists:
private List<Course> data;
private List<Object> ad;
You need to find a way to "collate" these down to a single list. Maybe something like this:
private static List<Object> collate(List<Course> data, List<Object> ads) {
List<Object> collated = new ArrayList<>();
while (data.size() > 0 || ads.size() > 0) {
for (int i = 0; i < ITEMS_PER_AD && data.size() > 0; ++i) {
collated.add(data.remove(0));
}
if (ads.size() > 0) {
collated.add(ads.remove(0));
}
}
return collated;
}
With that method defined, you can replace your existing constructor:
private List<Course> data;
private List<Object> ad;
// ...
public ViewCourseAdapter(Context context, List<Object> ad) {
this.data = new ArrayList<>();
this.ad = ad;
// ...
}
with this:
private List<Object> ad;
private List<Object> collated;
// ...
public ViewCourseAdapter(Context context, List<Object> ad) {
this.ad = ad;
this.collated = new ArrayList<>(ad);
// ...
}
And you can replace your existing setData()
method:
public void setData(List<Course> newData) {
if (data != null) {
CourseDiffCallback courseDiffCallback = new CourseDiffCallback(data, newData);
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(courseDiffCallback);
data.clear();
data.addAll(newData);
diffResult.dispatchUpdatesTo(this);
} else {
data = newData;
}
}
with this:
public void setData(List<Course> newData) {
if (data != null) {
List<Object> newCollated = collate(ad, newData);
// setup DiffUtil callback here...
this.collated = newCollated;
// dispatch DiffUtil result here...
}
}
Now you will have a single list that you can use in your adapter. Then you can change your adapter's methods to use that one list:
@Override
public int getItemCount() {
return collated.size();
}
@Override
public int getItemViewType(int position) {
return (collated.get(position) instanceof Course)
? COURSE_VIEW_TYPE
: AD_VIEW_TYPE;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == COURSE_VIEW_TYPE) {
bindCourseHolder((ViewCourseViewHolder) holder, position);
} else if (holder.getItemViewType() == AD_VIEW_TYPE) {
bindAdHolder((AdViewHolder) holder, position);
}
}
private void bindCourseHolder(ViewCourseViewHolder holder, int position) {
// ...
}
private void bindAdHolder(AdViewHolder holder, int position) {
// ...
}
All of these changes are based on the fundamental concept that you just have a single list, and that list holds (potentially) many different types of things.
Admob Banner Ads in Recyclerview
I used to work on this type of Recyclerview Adapters in the past. Hope this will help you
AdapterRecyclerView.java
public class AdapterRecyclerView extends RecyclerView.Adapter<AdapterRecyclerView.Holder> {
//private String url[];
private Context context;
private AdView mBannerAd;
int AD_TYPE = 0;
private Activity mainActivity;
private LayoutInflater inflater;
int CONTENT_TYPE = 1;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View v) {
super(v);
if (!(itemView instanceof AdView)) {
mTextView = (TextView) v.findViewById(R.id.text);
}
}
}
public AdapterRecyclerView(Context context) {
this.context = context;
// this.url = list;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
AdView adview;
ViewHolder holder;
if (viewType == AD_TYPE) {
adview = new AdView(mainActivity);
adview.setAdSize( AdSize.BANNER);
adview.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
float density = mainActivity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height);
adview.setLayoutParams(params);
AdRequest request = new AdRequest.Builder().build();
adview.loadAd(request);
return new Holder (adview);
}else{
View view = inflater.inflate(R.layout.recyclerview_row, parent, false);
return new Holder( view);
}
}
@Override
public void onBindViewHolder(@NonNull final Holder holder, final int position) {
if(position % 2 != 1) {
holder.titleView.setText(SplashScreen.newsList.get(position).getNewsTitle());
holder.detailsView.setText(SplashScreen.newsList.get(position).getNewsDetail());
Glide.with(context).load(SplashScreen.newsList.get(position).getNewsImageUrl()).into(holder.imgView);
holder.hiddenUrl.setText(SplashScreen.newsList.get(position).getNewsUrl());
holder.explore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), newsExplore.class);
myIntent.putExtra("newsUrl", SplashScreen.newsList.get(position).getNewsUrl());
v.getContext().startActivity(myIntent);
}
});
holder.share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent( Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "This news is shared using News app :: " + "\n\n" + SplashScreen.newsList.get(position).getNewsUrl();
sharingIntent.putExtra( Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra( Intent.EXTRA_TEXT, shareBody);
v.getContext().startActivity( Intent.createChooser(sharingIntent, "Share via"));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
Is there any way to Show Google Admob in Android Recycler View
Here is complete example. I just created an example app for you.
Main Activity
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class Main extends AppCompatActivity {
public static final String TAG = Main.class.getSimpleName();
private Context mContext;
private List<MyListModel> mList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mList = new ArrayList<MyListModel>();
for(int i=0;i<10;i++){
MyListModel myString = new MyListModel();
myString.setName(i+" - I love Paris");
myString.setViewType(1);
mList.add(myString);
}
//Place two Admob Ads at position index 1 and 5 in recyclerview
MyListModel myString1 = new MyListModel();
myString1.setViewType(2);
mList.add(1,myString1);
MyListModel myString2 = new MyListModel();
myString2.setViewType(2);
mList.add(5,myString2);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new ListAdopter(this, mList);
mRecyclerView.setAdapter(mAdapter);
}
}
RecyclerViewAdopter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.util.List;
public class RecyclerViewAdopter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private List<MyListModel> mList;
public RecyclerViewAdopter(Context mContext, List<MyListModel> mList) {
this.mList = mList;
this.mContext = mContext;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.listView_name);
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public AdView mAdView;
public ViewHolderAdMob(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch(viewType){
case 1:{
View v = inflater.inflate(R.layout.list_item_1, parent, false);
viewHolder = new MyViewHolder(v);
break;
}
case 2:{
View v = inflater.inflate(R.layout.list_item_admob, parent, false);
viewHolder = new ViewHolderAdMob(v);
break;
}
}
return viewHolder;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
MyListModel model = mList.get(holder.getAdapterPosition());
switch(holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.name.setText(model.getName());
break;
}
case 2:{
break;
}
}
}
@Override
public int getItemViewType(int position) {
return mList.get(position).getViewType();
}
@Override
public int getItemCount() {
return mList.size();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.kyanogen.ui.ScyllaListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:scrollbarThumbVertical="@color/primary_dark"
android:scrollbarStyle="insideInset"
android:scrollbarSize="4dp"
android:layout_below="@+id/toolbar"/>
</RelativeLayout>
list_item_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/listView_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="30dp"
android:textSize="16sp"/>
</LinearLayout>
list_item_admob.xml
<com.google.android.gms.ads.AdView
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="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
Update 9-12-2016
MyListModel
public class MyListModel {
private String name;
private int viewType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
}
How to create an Ad in RecyclerView?
You would like to check the item type of the RecyclerView
and then act accordingly. Use, the @Override
method,
@Override
public int getItemViewType(int position)
{
if (position % 5 == 0){
return AD_TYPE;
}else{
return CONTENT_TYPE;
}
}
Then you can bind the content or the Ad to the item in onCreateViewHolder
.
View view = null;
if (viewType == AD_TYPE)
{
view = new AdView(activity, AdSize.BANNER, ADMOB_ID);
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT,height);
view.setLayoutParams(params);
view.loadAd(new AdRequest());
}
else{
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_layout, viewGroup, false);
}
RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view);
return viewHolder;
This should do the job.
Also check out, this thread and this thread for more inputs. Similar questions as yours. The second one is exactly a copy of yours. Found it after answering your question.
How to make ads in RecyclerView display different contents
The solution might be very simple: less ads.
Even if you have 2500 items in your RecyclerView
, I highly doubt anyone will take the time to scroll through all of them. Most people will just view the first couple of items, although this might depend on the kind of content you're showing.
So I would suggest to only show ads in the first 50 (or something) items. And then lower the rate of the ads to like 1 in 100 or something. Or you could take a look at how Facebook is showing ads. And don't forget that people don't like ads!
But if you really want to show that much ads, you can also re-use some of them. It's not weird to show the same ads several times in a RecyclerView
with 2500 items.
Related Topics
How to Get String from Different Locales in Android
React-Native: Command Not Found
How to Change the Color of Header Bar and Address Bar in Newest Chrome Version on Lollipop
Android Command Line Tools Sdkmanager Always Shows: Warning: Could Not Create Settings
Android Listview Refresh Single Row
Apply a Theme to an Activity in Android
Android Push Notification (Gcm), Is There Any Daily Limit
Get Android API Level of Phone Currently Running My Application
How to Prevent a Service from Being Killed by Os
Enable and Disable a Broadcast Receiver
How to Pass Drawable Between Activities
How to Add Java.Awt.Image Package in Android
Why Does Eclipse Automatically Add Appcompat V7 Library Support Whenever I Create a New Project
Get Altitude by Longitude and Latitude in Android
How to Create Turn-By-Turn Gps Navigation App on Android/iOS Using Google Maps
No Internet on Android Emulator - Why and How to Fix