如何在不使用layout.xml的情况下以编程方式创建AdView

时间:2019-03-23 17:54:46

标签: java android android-layout admob

嗨,我已经尝试在此游戏中实施admob广告了一段时间了,我总是被mAdView = findViewById(R.id.adView);错误所阻止,整个游戏都是用Java编写的,并且我没有layout.xml文件< / p>

    RelativeLayout layout = new RelativeLayout(this);
    layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    mGLSurfaceView = new CCGLSurfaceView(this);

    // Create the adView
    AdView adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

    // Add the adView to it
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    adView.setLayoutParams(params);

    layout.addView(mGLSurfaceView);
    layout.addView(adView);

    setContentView(layout);
    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    mAdView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

3 个答案:

答案 0 :(得分:1)

我刚刚找到了答案,而你不知道我没有尝试过它是多么愚蠢。解决方案是简单地将其从代码中删除“ mAdView = findViewById(R.id.adView);”

答案 1 :(得分:0)

尝试类似的东西-

   AdView mAdView = new AdView(activity);
   RelativeLayout.LayoutParams params =  new RelativeLayout
        .LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
   params.addRule(RelativeLayout.CENTER_HORIZONTAL);
   params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
   mAdView.setLayoutParams(params);
   mAdView.setId(R.id.adView);
   mAdView.setAdSize(AdSize.SMART_BANNER);
   mAdView.setAdUnitId(activity.getString(R.string.banner_ad_unit_id));
   adLayout.removeView(activity.findViewById(R.id.adView));
   adLayout.addView(mAdView);;
   AdRequest adRequest = new AdRequest.Builder().build();
   mAdView.loadAd(adRequest);

有关更多信息,请检查-https://www.concretepage.com/questions/429

答案 2 :(得分:0)

如果要用代码创建所有内容;那么需要添加此行吗?

mAdView = findViewById(R.id.adView);

删除此按钮,您就很高兴了。