2017-07-19 17 views
0

我有一個有兩列的GridView,我想在每第n行後顯示一個原生廣告。我在互聯網上搜索了很多,但找不到任何解決方案。Android:如何在GridView中每排第n行之後連續顯示AdView?

我已經嘗試了幾個庫/ sdks,如https://github.com/clockbyte/admobadapter,但一直無法解決我的問題。

代碼嘗試:

public View getView(final int position, View row, ViewGroup parent) { 
     MyHolder holder = null; 
     boolean showAd = proVersion == false && (position % 8 == k); 
     if (showAd) { 
      AdView adView = adList.get(position); 
      if (adView == null) { 
       AdView adViewNew = new AdView((Activity) context, AdSize.BANNER, context.getResources().getString(
         R.string.adId)); 
       adViewNew.loadAd(Utils.getAdRequest("gps", lat, lng, keywords)); 
       adList.add(position, adViewNew); 
       return adViewNew; 
      } else { 
       return adView; 
      } 
     } else if (row == null || row instanceof AdView) { 
      LayoutInflater inflater = ((SherlockActivity) context).getLayoutInflater(); 
      row = inflater.inflate(viewResourceId, parent, false); 
      holder = new MyHolder(); 
      holder.textName = (TextView) row.findViewById(R.id.name); 
      row.setTag(holder); 
     } else { 
      holder = (MyHolder) row.getTag(); 
     } 
     holder.textName.setText(items.get(position).getName()); 

     // more code 

     return row; 
    } 

I want to achieve something like this:

+1

你有沒有試過?我的意思是不只是lib網址,但代碼 – Vyacheslav

+0

@Vyacheslav我提供了一個代碼嘗試以及 –

+0

是'if(showAd){'被解僱或沒有? – Vyacheslav

回答

0

我不知道你的代碼,但。

簡而言之。

  1. 創建擴展BaseAdapter的自定義適配器。

  2. 創建自己的類來存儲您的GridViewCell數據。

例如,

class MyStoredData { 
public String myTextOfUsualElement = ""; 
public boolean isThisBannerElement = false;//or true if this row is banner 
//the other setup 
} 
  • 內部getView()檢查,如果該元素是橫幅:
  • @Override 公共視圖getView(INT位置,查看convertView,父的ViewGroup){

    if (myStoredDataArrayList.get(position).isThisBannerElement) { 
    //inflate here your banner 
    } else { 
    //inflate here your usual info 
    } 
    //... 
        } 
    

    爲了合併行,請,REA d此答案

    https://stackoverflow.com/a/12554312/1979882或者使用TableLayout來代替。

    +0

    您能否介紹一下如何使廣告適合整個網格行而不是單個網格單元?謝謝 –

    0

    AdmobAdapter示例工作正常。 方法initRecyclerViewItems()需要更新MainActivity_RecyclerView_Express文件。

    /*Code to be replaced*/ 
    rvMessages.setLayoutManager(new LinearLayoutManager(this)); 
    
    /*Replace the above code with the below one*/ 
    final GridLayoutManager layoutManager = new GridLayoutManager(this, 2); 
    rvMessages.setLayoutManager(layoutManager); 
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { 
        @Override 
        public int getSpanSize(int position) { 
         switch (rvMessages.getAdapter().getItemViewType(position)) { 
          case 1: 
           return 2; 
    
          default: 
           return 1; 
         } 
    
    
        } 
    }); 
    
    相關問題