Android:如何在GridView中的每第n行之后连续显示AdView?

时间:2017-07-19 05:27:13

标签: android gridview admob

我有一个包含两列的GridView,我希望在每第n行后显示一个原生广告。我在互联网上搜索了很多,但找不到任何解决方案。

我尝试了一些类似https://github.com/clockbyte/admobadapter的库/ sdks,但无法解决我的问题。

代码尝试:

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:

2 个答案:

答案 0 :(得分:0)

我不知道你的代码。

简而言之。

  1. 创建扩展BaseAdapter的自定义适配器。

  2. 创建自己的类,用于存储GridViewCell数据。

  3. e.g。

    class MyStoredData {
    public String myTextOfUsualElement = "";
    public boolean isThisBannerElement = false;//or true if this row is banner
    //the other setup
    }
    
    1. getView()内检查此元素是否为横幅:
    2.   

      @覆盖           public View getView(int position,View convertView,ViewGroup parent){

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

      为了合并行,请阅读此答案

      https://stackoverflow.com/a/12554312/1979882或使用TableLayout。

答案 1 :(得分: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;
        }


    }
});