Search code examples
androidandroid-recyclerviewadmobstaggeredgridlayout

Is it possible to use admob native ads with StaggeredGridLayoutManager?


I follow the firebase admob guides to add admob advanced native ads to my recyclerviewadapter. I can easily display ads with medium and big ads type. But my app also include staggered grid as view type. But i cannot display ads with this format and i can only see white screen in ads row. I think this is size issue but there is no size for staggered row format in admob. It limits me minumum width value of 280dp. Is there any way to display ads in staggered format? If there is not,than Can you advice me another ads provider like admob to solve this problem?


Solution

  • I solved this problem using GridLayoutManager instead of StaggeredGridLayoutManager thanks to Chris in this google groups answer.

    Here is Solution

      public static final int ITEMS_PER_AD = 8;
    
      private GridLayoutManager mLayoutManager;
    
      // The Native Express ad height.
      private static final int NATIVE_EXPRESS_AD_HEIGHT = 150;
    
     // The Native Express ad unit ID.
     private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1072772517";
    
     // The RecyclerView that holds and displays Native Express ads and menu items.
     private RecyclerView mRecyclerView;
    
     // List of Native Express ads and MenuItems that populate the RecyclerView.
     private List<Object> mRecyclerViewItems = new ArrayList<>();
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLayoutManager = new GridLayoutManager(this, 2);
        mLayoutManager.setSpanSizeLookup(new 
        GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position % MainActivity.ITEMS_PER_AD == 0) {
                return 2;
            }
            return 1;
        }
        });
    
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    
        // Use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView.
        mRecyclerView.setHasFixedSize(true);
    
        // Specify a linear layout manager.
        mRecyclerView.setLayoutManager(mLayoutManager);
    
       // Update the RecyclerView item's list with menu items and Native Express ads.
       addMenuItemsFromJson();
       addNativeExpressAds();
       setUpAndLoadNativeExpressAds();
    
       // Specify an adapter.
       RecyclerView.Adapter adapter = new RecyclerViewAdapter(this, mRecyclerViewItems);
       mRecyclerView.setAdapter(adapter);
    }
    

    If you can follow the this sample project, you can find other class and layout. Because this is modified version of this project. I hope this solution works others like me.