Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

android - How to put an Interstital Ad inside an adapter class?

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

Does anyone know how to show an ad before these new activities are loaded?

As you can see, I have an adapter called CustomSwipeAdapterCovers and it is responsible for opening the new activities, and in MainActivity show how the ad is loaded, but I don't know how to implement ads on non-activities.

public class MainActivity extends AppCompatActivity {


    private static final int START_LEVEL = 1;
    private int mLevel;
    private Button mNextLevelButton;
    private InterstitialAd mInterstitialAd;
    private TextView mLevelTextView;


    private ViewPager viewPager;
    private CustomSwipeAdapterCapas adapter;



    //=================================

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the next level button, which tries to show an interstitial when clicked.
        mNextLevelButton = ((Button) findViewById(R.id.next_level_button));
        mNextLevelButton.setEnabled(false);
        mNextLevelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInterstitial();
            }
        });



        // Create the text view to show the level number.
        mLevelTextView = (TextView) findViewById(R.id.level);
        mLevel = START_LEVEL;

        // Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();

        // Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
        Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();



        viewPager = findViewById(R.id.viewpager_main_xml);
        adapter = new CustomSwipeAdapterCapas(this);
        viewPager.setAdapter(adapter);

    }




   //=====================================

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    private InterstitialAd newInterstitialAd() {
        InterstitialAd interstitialAd = new InterstitialAd(this);
        interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mNextLevelButton.setEnabled(true);
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                mNextLevelButton.setEnabled(true);
            }

            @Override
            public void onAdClosed() {
                // Proceed to the next level.
                goToNextLevel();
            }
        });
        return interstitialAd;
    }

    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and reload the ad.
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        } else {
            Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
            goToNextLevel();
        }
    }

    private void loadInterstitial() {
        // Disable the next level button and load the ad.
        mNextLevelButton.setEnabled(false);
        AdRequest adRequest = new AdRequest.Builder()
                .setRequestAgent("android_studio:ad_template").build();
        mInterstitialAd.loadAd(adRequest);
    }

    private void goToNextLevel() {
        // Show the next level and reload the ad to prepare for the level after.
        mLevelTextView.setText("Level " + (++mLevel));
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

}

public class CustomSwipeAdapterCovers extends PagerAdapter {



    private int[] BookCovers = {   R.drawable.cover_1,
                                    R.drawable.cover_2,
                                    R.drawable.cover_3,
                                    R.drawable.capa_4,
                                    R.drawable.capa_5,
                                    R.drawable.capa_6,
                                    R.drawable.capa_7,
                                    R.drawable.capa_8,
                                    R.drawable.capa_9,
                                    R.drawable.capa_10,
                                    R.drawable.capa_11,
                                    R.drawable.capa_12,};

    private Context context;
    private LayoutInflater layoutInflater;

    public CustomSwipeAdapterCapas(Context context){

        this.context = context;

    }


    @Override
    public int getCount() {
        return capasLivros.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == (LinearLayout) object);
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.capas_layout, container, false);
        ImageButton imageButton = item_view.findViewById(R.id.imagebutton_main_xml);
        imageButton.setImageResource(BookCovers[position]);


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if( position == 0){


                    Intent intent = new Intent(v.getContext(), LivroUmActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 1){


                    Intent intent = new Intent(v.getContext(), LivroDoisActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 2){

                    Intent intent = new Intent(v.getContext(), LivroTresActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 3){

                    Intent intent = new Intent(v.getContext(), LivroQuatroActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 4){

                    Intent intent = new Intent(v.getContext(), LivroCincoActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 5){

                    Intent intent = new Intent(v.getContext(), LivroSeisActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 6){

                    Intent intent = new Intent(v.getContext(), LivroSeteActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 7){

                    Intent intent = new Intent(v.getContext(), LivroOitoActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 8){

                    Intent intent = new Intent(v.getContext(), LivroNoveActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 9){

                    Intent intent = new Intent(v.getContext(), LivroDezActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 10){

                    Intent intent = new Intent(v.getContext(), LivroOnzeActivity.class);
                    v.getContext().startActivity(intent);

                } else if(position == 11){

                    Intent intent = new Intent(v.getContext(), LivroDozeActivity.class);
                    v.getContext().startActivity(intent);

                }

            }
        });


        container.addView(item_view);
        return item_view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
        //super.destroyItem(container, position, object);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...