如何在recyclerview中限制原生广告的数量

时间:2017-09-21 08:46:25

标签: android recycler-adapter google-admob

如何在recyclerview中限制原生广告的数量 我只想在recyclerview的前100行中使用5个原生广告(每20行一次)。 我的Recyclerview有10000排。它每20行广告输出就会使用户烦恼。所以我想将广告数量限制为5.我做了很多改变,但我做不到。 提前感谢您的帮助

我的活动中与广告相关的部分

public static final int ITEMS_PER_AD = 20;
private static final int NATIVE_EXPRESS_AD_HEIGHT = 100;

private void addNativeExpressAds() {

        // Loop through the items array and place a new Native Express ad in every ith position in
        // the items List.
        for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
            final NativeExpressAdView adView = new NativeExpressAdView(getActivity());
            mRecyclerViewItems.add(i, adView);
        }
    }
    private void setUpAndLoadNativeExpressAds() {
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
                        final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
                        AdSize adSize = new AdSize(AdSize.FULL_WIDTH, NATIVE_EXPRESS_AD_HEIGHT);
                        adView.setAdSize(adSize);
                        adView.setAdUnitId(AD_UNIT_ID);
                    }
                    loadNativeExpressAd(0);
                }catch (Exception e){

                }

            }
        });
    }
    private void loadNativeExpressAd(final int index) {

//        if (index >= mRecyclerViewItems.size()) {
//            return;
//        }

        if (index >= mRecyclerViewItems.size()) {
            return;
        }

        Object item = mRecyclerViewItems.get(index);
        if (!(item instanceof NativeExpressAdView)) {
            throw new ClassCastException("Expected item at index " + index + " to be a Native"
                    + " Express ad.");
        }

        final NativeExpressAdView adView = (NativeExpressAdView) item;
        // Set an AdListener on the NativeExpressAdView to wait for the previous Native Express ad
        // to finish loading before loading the next ad in the items list.
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                // The previous Native Express ad loaded successfully, call this method again to
                // load the next ad in the items list.
                if (index<24){
                loadNativeExpressAd(index + ITEMS_PER_AD);
                }
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // The previous Native Express ad failed to load. Call this method again to load
                // the next ad in the items list.
                Log.e("MainActivity", "The previous Native Express ad failed to load. Attempting to"
                        + " load the next Native Express ad in the items list.");
                //loadNativeExpressAd(index + ITEMS_PER_AD);
            }
        });
        try {
            adView.loadAd(new AdRequest.Builder().build());
        }catch (Exception e){}

    }

和我的RecyclerViewAdapter.java

class RecyclerViewAdapter extends FastScrollRecyclerView.Adapter<RecyclerView.ViewHolder>  {
    private static final int MENU_ITEM_VIEW_TYPE = 0;
    private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
    private final Context mContext;
    private final List<Object> mRecyclerViewItems;

    ItemClickListener listener;
    public RecyclerViewAdapter(Context context, List<Object> recyclerViewItems, ItemClickListener listener) {
        this.mContext = context;
        this.mRecyclerViewItems = recyclerViewItems;
        this.listener=listener;
    }

    public class MenuItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView menuItemName;
        private TextView menuItemDescription;
        private TextView menuItemPrice;
        private TextView menuItemCategory;
        private ImageView menuItemImage;
        ItemClickListener itemClickListener;

        MenuItemViewHolder(View view) {
            super(view);
            menuItemImage = (ImageView) view.findViewById(R.id.cinsiyetresmi);
            menuItemName = (TextView) view.findViewById(R.id.menu_item_name);
            menuItemPrice = (TextView) view.findViewById(R.id.menu_item_price);
            menuItemCategory = (TextView) view.findViewById(R.id.menu_item_category);
            menuItemDescription = (TextView) view.findViewById(R.id.menu_item_description);
            view.setOnClickListener(this);
        }
        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }

        public void setItemClickListener(ItemClickListener ic)
        {
            this.itemClickListener=ic;

        }
    }

    public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder  {

        NativeExpressAdViewHolder(View view) {
            super(view);
        }

    }

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

    @Override
    public int getItemViewType(int position) {
        return (position % isimler_erkek.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
                : MENU_ITEM_VIEW_TYPE;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        switch (viewType) {
            case MENU_ITEM_VIEW_TYPE:
                View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
                        R.layout.menu_item_container, viewGroup, false);
                return new MenuItemViewHolder(menuItemLayoutView);
            case NATIVE_EXPRESS_AD_VIEW_TYPE:
                // fall through
            default:
                View nativeExpressLayoutView = LayoutInflater.from(
                        viewGroup.getContext()).inflate(R.layout.native_express_ad_container,
                        viewGroup, false);
                return new NativeExpressAdViewHolder(nativeExpressLayoutView);
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        MenuItem menuItem;
        MenuItemViewHolder menuItemHolder;
        switch (viewType) {
            case MENU_ITEM_VIEW_TYPE:
                menuItemHolder = (MenuItemViewHolder) holder;
                menuItem = (MenuItem) mRecyclerViewItems.get(position);

                // Get the menu item image resource ID.
                String imageName = menuItem.getImageName();
                int imageResID = mContext.getResources().getIdentifier(imageName, "drawable",
                        mContext.getPackageName());

                // Add the menu item details to the menu item view.
                menuItemHolder.menuItemImage.setImageResource(imageResID);
                menuItemHolder.menuItemName.setText(menuItem.getName());
                menuItemHolder.menuItemPrice.setText(menuItem.getPrice());
                menuItemHolder.menuItemCategory.setText(menuItem.getCategory());


                menuItemHolder.menuItemDescription.setText(menuItem.getDescription());
                final  int idsi= Integer.parseInt(menuItem.getDescription());
                menuItemHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onItemClick(View v, int pos) {
                        //Snackbar.make(v,String.valueOf(players.get(pos).getId()), Snackbar.LENGTH_SHORT).show();
                        try {
                            listener.onItemClick(v,idsi);
                        }
                        catch (Exception e){
                        }
                        //Toast.makeText(this.getApplicationContext(), "bak", Toast.LENGTH_LONG).show();
                    }
                });

                break;
            case NATIVE_EXPRESS_AD_VIEW_TYPE:
                // fall through
            default:

                    NativeExpressAdViewHolder nativeExpressHolder =
                            (NativeExpressAdViewHolder) holder;
                    NativeExpressAdView adView =
                            (NativeExpressAdView) mRecyclerViewItems.get(position);
                    ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;

                    if (adCardView.getChildCount() > 0) {
                        adCardView.removeAllViews();
                    }
                    if (adView.getParent() != null) {
                        ((ViewGroup) adView.getParent()).removeView(adView);
                    }

                    // Add the Native Express ad to the native express ad view.
                    adCardView.addView(adView);

        }
    }

}

1 个答案:

答案 0 :(得分:0)

private View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterVideo mAdapter;
private SwipeRefreshLayout swipe_refresh;
private Call<CallbackRecent> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
int counter = 1;

private List<Object> ViewItems = new ArrayList<>();

// List of native ads that have been successfully loaded.
private List<UnifiedNativeAd> mNativeAds = new ArrayList<>();
// The AdLoader used to load ads.
private AdLoader adLoader;

// The number of native ads to load.
public static final int NUMBER_OF_ADS = 4;

// The number of Items to Show Native Between Items.
public static final int NUMBER_OF_ROW = 2;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root_view = inflater.inflate(R.layout.fragment_video, null);
    parent_view = getActivity().findViewById(R.id.main_content);



    loadInterstitialAd();

    // Update the RecyclerView item's list with native ads.
    loadNativeAds();


    swipe_refresh = root_view.findViewById(R.id.swipe_refresh_layout_home);
    swipe_refresh.setColorSchemeResources(R.color.colorOrange, R.color.colorGreen, R.color.colorBlue, R.color.colorRed);
    recyclerView = root_view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setHasFixedSize(true);



    //set data and list adapter
   // mAdapter = new AdapterVideo(getActivity(), recyclerView, new ArrayList<News>());
    mAdapter = new AdapterVideo(getActivity(), recyclerView, ViewItems);
    recyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();




    if (Config.ENABLE_RTL_MODE) {
        recyclerView.setRotationY(180);
    }

    // on item list clicked
    mAdapter.setOnItemClickListener(new AdapterVideo.OnItemClickListener() {
        @Override
        public void onItemClick(View v, News obj, int position) {
            ActivityNewsDetail.navigate((MainActivity) getActivity(), v.findViewById(R.id.image), obj);
            showInterstitialAd();
        }
    });

    // detect when scroll reach bottom
    mAdapter.setOnLoadMoreListener(new AdapterVideo.OnLoadMoreListener() {
        @Override
        public void onLoadMore(int current_page) {
            if (post_total > mAdapter.getItemCount() && current_page != 0) {
                int next_page = current_page + 1;
                requestAction(next_page);
            } else {
                mAdapter.setLoaded();
            }
        }
    });

    // on swipe list
    swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
            mAdapter.resetListData();
            requestAction(1);

        }
    });

    requestAction(1);
    getAllVideo();


    return root_view;
}

private void getAllVideo(){

    if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
    mAdapter.resetListData();
    requestAction(1);
}

private void displayApiResult(final List<News> posts) {
    mAdapter.insertData(posts);
    swipeProgress(false);
    if (posts.size() == 0) {
        showNoItemView(true);
    }
}

private void requestListPostApi(final int page_no) {
    ApiInterface apiInterface = RestAdapter.createAPI();
    callbackCall = apiInterface.getVideoPost(page_no, Config.LOAD_MORE);
    callbackCall.enqueue(new Callback<CallbackRecent>() {
        @Override
        public void onResponse(Call<CallbackRecent> call, Response<CallbackRecent> response) {
            CallbackRecent resp = response.body();
            if (resp != null && resp.status.equals("ok")) {
                post_total = resp.count_total;
                displayApiResult(resp.posts);

            } else {
                onFailRequest(page_no);
            }
        }

        @Override
        public void onFailure(Call<CallbackRecent> call, Throwable t) {
            if (!call.isCanceled()) onFailRequest(page_no);
        }

    });
}

private void onFailRequest(int page_no) {
    failed_page = page_no;
    mAdapter.setLoaded();
    swipeProgress(false);
    if (NetworkCheck.isConnect(getActivity())) {
        showFailedView(true, getString(R.string.msg_no_network));
    } else {
        showFailedView(true, getString(R.string.msg_offline));
    }
}

private void requestAction(final int page_no) {
    showFailedView(false, "");
    showNoItemView(false);
    if (page_no == 1) {
        swipeProgress(true);
    } else {
        mAdapter.setLoading();

    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            requestListPostApi(page_no);
        }
    }, Constant.DELAY_TIME);
}

@Override
public void onDestroy() {
    super.onDestroy();
    swipeProgress(false);
    if (callbackCall != null && callbackCall.isExecuted()) {
        callbackCall.cancel();
    }
}

private void showFailedView(boolean show, String message) {
    View lyt_failed = root_view.findViewById(R.id.lyt_failed_home);
    ((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
    if (show) {
        recyclerView.setVisibility(View.GONE);
        lyt_failed.setVisibility(View.VISIBLE);
    } else {
        recyclerView.setVisibility(View.VISIBLE);
        lyt_failed.setVisibility(View.GONE);
    }
    root_view.findViewById(R.id.failed_retry).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            requestAction(failed_page);
        }
    });
}

private void showNoItemView(boolean show) {
    View lyt_no_item = root_view.findViewById(R.id.lyt_no_item_home);
    ((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.msg_no_news);
    if (show) {
        recyclerView.setVisibility(View.GONE);
        lyt_no_item.setVisibility(View.VISIBLE);
    } else {
        recyclerView.setVisibility(View.VISIBLE);
        lyt_no_item.setVisibility(View.GONE);
    }
}

private void swipeProgress(final boolean show) {
    if (!show) {
        swipe_refresh.setRefreshing(show);
        return;
    }
    swipe_refresh.post(new Runnable() {
        @Override
        public void run() {
            swipe_refresh.setRefreshing(show);
        }
    });
}

private void loadInterstitialAd() {
    if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
        MobileAds.initialize(getActivity(), getResources().getString(R.string.admob_app_id));
        interstitialAd = new InterstitialAd(getActivity());
        interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
        interstitialAd.loadAd(Tools.getAdRequest(getActivity()));
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                interstitialAd.loadAd(new AdRequest.Builder().build());
            }
        });
    }
}

private void showInterstitialAd() {
    if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
        if (interstitialAd != null && interstitialAd.isLoaded()) {
            if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
                interstitialAd.show();
                counter = 1;
            } else {
                counter++;
            }
        }
    }
}


private void loadNativeAds() {

    AdLoader.Builder builder = new AdLoader.Builder(getActivity(), getString(R.string.admob_native_unit_id));
    adLoader = builder.forUnifiedNativeAd(
            new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
                @Override
                public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
                    // A native ad loaded successfully
                    mNativeAds.add(unifiedNativeAd);
                    if (!adLoader.isLoading()) {

                        insertAdsInMenuItems(); //Show Native Inside Items RecyclerView
                    }
                }
            }).withAdListener(
            new AdListener() {
                @Override
                public void onAdFailedToLoad(int errorCode) {
                    // A native ad failed to load, check if the ad loader has finished loading
                    Log.e("MainActivity", "The previous native ad failed to load. Attempting to"
                            + " load another.");
                    if (!adLoader.isLoading()) {
                        insertAdsInMenuItems(); //Show Native Inside Items RecyclerView
                    }
                }
            }).build();

    // Load the Native ads.
    adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS);

}

// Method To Add native Inside Items :
private void insertAdsInMenuItems() {
    if (mNativeAds.size() <= 0) {
        return;
    }



    int offset = (ViewItems.size() / mNativeAds.size()) + NUMBER_OF_ROW;

    int index = 0;

    for (UnifiedNativeAd ad : mNativeAds) {
        ViewItems.add(index, ad);
        index = index + offset;
    }

}