简体   繁体   中英

Adding an Admob banner to a listview every X rows

I know this question has been asked multiple times. I have gone through a lot of the tickets here on stackover flow and I cannot seem to find anything that I can clearly understand. I have been able to get an Admob Banner to appear in my app, but I am unable to figure out how to get it into my listview. I pointers and/or help would be greatly appreciated.

Putting an AdMob native ad in a listView

Here is my adapter where I want the banner ad to appear.

@Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        League league = leaguesList.get(position);



        if (position == 0) {
            // Create and return Ad View
            //int id = league.getId();
            //String leagueId = String.valueOf(id);
            //holder.id.setText(leagueId);
            holder.name.setText("BANNER GOES HERE");
        } else {
            // Create and return a normal View
            int id = league.getId();
            String leagueId = String.valueOf(id);
            holder.id.setText(leagueId);
            holder.name.setText(league.getName());
        }



        //Formatting And Displaying Timestamp
        holder.timestamp.setText(formatDate(league.getTimestamp()));
    }

This is my code for the banner ad

// Initialize the Mobile Ads SDK

        //setContentView(R.layout.content_main);
        MobileAds.initialize(this,
                getString(R.string.admob_app_id));

        // Find Banner ad
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        // Display Banner ad
        mAdView.loadAd(adRequest);
    }

I am not sure how to incorporate the ad code into the view holder inorder to make it work.

Again any assistance would be appreciated.

League Adapter Code (Modified)

    public class LeagueAdapter extends RecyclerView.Adapter<LeagueAdapter.MyViewHolder> {

    private Context context;
    private List<League> leaguesList;

    public void notifyDatasetChanged(List<League> newleagueslist) {
        leaguesList.clear();
        leaguesList.addAll(newleagueslist);
        super.notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        private TextView leagueAverage;
        public TextView id;
        public TextView timestamp;

        public MyViewHolder(View view) {
            super(view);
            id = view.findViewById( R.id.tvLeagueId);
            name = view.findViewById(R.id.tvSeriesName );
            leagueAverage = view.findViewById(R.id.tvLeagueAverage);
            timestamp = view.findViewById(R.id.timestamp);
        }
    }


    public LeagueAdapter(Context context, List<League> leaguesList) {
        this.context = context;
        this.leaguesList = leaguesList;
    }

    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 MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //View itemView = LayoutInflater.from(parent.getContext())
        //        .inflate(R.layout.listview_league, parent, false);
        RecyclerView.ViewHolder viewHolder;
         viewHolder = null;
         LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        switch(viewType){
            case 1:{
                View v = inflater.inflate(R.layout.listview_league, parent, false);
                viewHolder = new MyViewHolder(v);
                break;
            }
            case 2:{
                View v = inflater.inflate(R.layout.listview_league_admob, parent, false);
                viewHolder = new ViewHolderAdMob(v);
               break;
          }
       }
       //return (MyViewHolder) itemView;

       return new MyViewHolder(viewHolder);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        //League league = leaguesList.get(position);

        League league1 = leaguesList.get(holder.getAdapterPosition());

        switch(holder.getItemViewType()){
            case 1:{
                MyViewHolder viewHolder = (MyViewHolder) holder;
                viewHolder.name.setText(league1.getName());
                viewHolder.timestamp.setText(formatDate(league1.getTimestamp()));
                break;
            }
            case 2:{
                break;
            }
        }

    }

    @Override
    public int getItemCount() {
        return leaguesList.size();
    }

    //Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
    //Input  : 2018-05-23 9:59:01
    //Output : Wed May 23 2018 (9:59:01)
    private String formatDate(String dateStr) {
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = fmt.parse(dateStr);
            SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
            return fmtOut.format(date);
        } catch (ParseException e) {

        }

        return "";
    }
}

Layout XML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:autofit="http://schemas.android.com/apk/res-auto"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground"
    android:paddingBottom="@dimen/dimen_10"
    android:paddingLeft="@dimen/activity_margin"
    android:paddingRight="@dimen/activity_margin"
    android:paddingTop="@dimen/dimen_10"
    android:focusable="true">

    <me.grantland.widget.AutofitTextView
        android:id="@+id/tvSeriesName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:singleLine="true"
        android:text="@string/leagueValue"
        android:textColor="?attr/colorText1"
        android:textSize="24sp"
        autofit:minTextSize="16sp" />

    <TextView
        android:id="@+id/tvLeagueAverage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tvSeriesName"
        android:layout_marginStart="0dp"
        android:text="League Average: 300"
        android:textColor="#000000"
        android:textSize="18sp"
        android:visibility="gone" />

    <TextView
        android:id="@+id/timestamp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvSeriesName"
        android:layout_centerHorizontal="true"
        android:text="Fri May 18 2018"
        android:textColor="?attr/colorText1"
        android:textSize="10sp"
        android:visibility="gone" />

    <TextView
        android:id="@+id/tvLeagueId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/tvSeriesName"
        android:layout_below="@+id/timestamp"
        android:text="TextView"
        android:textColor="?attr/colorText1"
        android:visibility="gone" />

    <!-- set Banner ad position in UI layout design -->
    <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_alignParentBottom="false"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/admob_banner_id" />

</RelativeLayout>

This can be achieved in many ways. The simplest one is adding the adview inside the list item layout itself and making it visible or invisible from onBindViewHolder. You can add an additional integer variable say 'viewType' to the League class inorder to identify whether the actual row item to show or the adview to show. Before passing the list to adapter, iterate through list and add an item for advertisement at intervals you need. Then you can simply check the viewType and show or hide adview and real row item content.

Inside Activity / Fragment (Before sending list data to Adapters constructor)

int interval = 0;
for(League model : oldList){
   if(interval == 5){
      list.add(new League(1, param, param));
      interval = 0;
   }else{
      model.setType(0);
      interval ++;
   }
   list.add(model);
}

set adapter after the above code.

You don't have to write the iteration code in onBindViewHolder. Your onBindViewHolder must look like this

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    League league = leaguesList.get(position);

    if(league.getType() == 1){
        //Adview. Shoe Adview and hide item viewgroup / items
    }else{
        //Row item content. Hide Adview and show item viewgroup / items
    }
}

My idea is to Override getItemViewType and return another type for each even position (%).

In onCreateViewHolder use viewType to deltermine which viewHolder you gonna use. You should have two viewHolder's with different layouts (or one with set visibility). One viewHolder will be a normal item of your list. the second one will hold adView.

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM