How to put an Interstital Ad inside an adapter class?

前端 未结 2 597
北荒
北荒 2020-12-20 09:00

I have a ViewPager in MainActivity that open a new Activity when you touch each image that is inside an adapter.

Does anyone k

2条回答
  •  攒了一身酷
    2020-12-20 09:02

    you should do like following code.... Declare this code in adapter class at the top... private InterstitialAd mInterstitialAd;

    After this you put the rest of the code in your onBindViewHolder()

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, final int position) {
    
        Picasso.get()
                .load(picsArray[position])
                .into(holder.imageView);
    
        mInterstitialAd = new InterstitialAd(context);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
    
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }
    
            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }
    
            @Override
            public void onAdOpened() {
                // Code to be executed when the ad is displayed.
            }
    
            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }
    
            @Override
            public void onAdClosed() {
                Intent intent = new Intent(context, Full_Image_Activity.class);
                intent.putExtra("IMG",picsArray[position]);
                context.startActivity(intent);
    

    ///// onAdClosed() method you can put your intent or what ever you want, this is for when you close the add then the intent must know what to do... } });

    }
    

    After this you can put the code in your item.onClicklistner method like below..

    itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    } else {
                        Intent intent = new Intent(context, Full_Image_Activity.class);
                        intent.putExtra("IMG",picsArray[getAdapterPosition()]);
                        context.startActivity(intent);
                    }
    
                }
            });
    

    In the else{} you can put your code like intent or whatever you want to do... Hope it will work for many peoples...

提交回复
热议问题