简体   繁体   中英

How can I add the interstitial ads

I want to show an interstitial ad when the button is clicked in an adapter file. This adapter file is connected directly to a button in activity_main.xml. How can I show the interstitial ad when clicking this button?

Edit//

When I enter Admob ad codes, it asks me to enter an activity for the.show code, but since this is an adapter file, I cannot use activity. interstitialAd.show (TracksAdapter.class); I don't know what to use instead of TracksAdapter here. How can I run ad codes?

Thanks!

AdapterFile;

public class TracksAdapter extends BaseAdapter {

    Context context;



public View getView(int position, View convertView, ViewGroup parent) {
        MobileAds.initialize(context, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {}
        });


     holder.file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    Intent intent = new Intent(context.getApplicationContext(), TestActivity.class);
                    intent.putExtra(TrackingActivity.EXTRA_TRACK_KEY, holder.id);
                    intent.putExtra(TrackingActivity.TRACKSKEY, holder.id);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    intent.putExtra("name", holder.names);
                    intent.putExtra("phone", holder.phones);
                    intent.putExtra("lastseen", holder.lastseens);
                    intent.putExtra("membership", holder.membership);

                    context.getApplicationContext().startActivity(intent);


            }
        });
        return convertView;
    }

According to documentation the "show()" method has one parameter;

activity An Activity context from which to present the ad.

You need to pass your Activity's context here. A simple demonstration can be like this;

MainActivity.java

...
//You can pass your activity's contex by using the adapter's constructor method.
TracksAdapter adapter = new TracksAdapter(MainActivity.this);
...

TracksAdapter.java

private Activity activity;

protected void TracksAdapter(Activity activity){
    this.activity = activity;
}

...

//in your onClick
void onClick(View v){
    //initialization etc.
    ...
    //Pass your activity's context
    interstitialAd.show (activity);
}

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