任何方法都可以在不使用布局文件(xml)的情况下使用admob中的NativeExpressAdView
。
我只使用java文件创建视图,并想知道如何从NativeExpressAdView
的java文件创建视图?
修改
我试过这个
NativeExpressAdView adView = new NativeExpressAdView(activity);
AdSize adSize = new AdSize(280, 80);
adView.setAdSize(adSize);
adView.setAdUnitId(getString(R.string.ad_unit_id));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, adSize.getHeightInPixels(activity));
adView.setLayoutParams(layoutParams);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
linear_layout.addView(adView);
此代码为我提供了一个黑色的空视图width:280dp, height: 80dp
答案 0 :(得分:0)
这样的事情应该有用......首先"预留"通过创建文件/res/values/ids.xml
来获取视图的ID:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="nativeExpressAdId" type="id"/>
</resources>
在Android版的API&gt;上17你可以generate the ID on the fly,但是你失去了向后兼容性。
接下来在&#39; / res / values / strings.xml`中添加一个条目:
<string name="adUnitId">ca-app-pub-12345678901234567890etc</string>
然后在代码中:
NativeExpressAdView adView = new NativeExpressAdView(this);
adView.setId(R.id.nativeExpressAdId);
int height = 80; // or whatever is appropriate - make sure its >= ad minimum
// set the size to the width of the screen
adView.setAdSize(new AdSize((int) (AdSize.FULL_WIDTH, height));
adView.setAdUnitId(getString(R.string.adUnitId));
// assuming this goes in a linearlayout... you can also addRules to lp
LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
// set margins manually (`.setMargins()`) or add rules with (`.addRule()`)
// or .setVisibility() etc... to lp
adView.setLayoutParams(lp);
然后使用parent.addView(adView)
将其插入父容器。这不完全是我使用的代码(我使用的是RelativeLayout),但它非常接近,所以应该让你开始。
如果您需要在轮播时生成新广告,则此类代码非常有用,因为您无法调整现有广告的大小。你可以借#34;之前的ID,可见性,布局等,并将其应用于新的ID。有关类似示例,请参阅here。
提示:请确保在删除nativeexpressadview之前停止所有正在运行的动画,因为这可能会导致旧版网页中的崩溃,例如kitkat中的崩溃。
答案 1 :(得分:0)
这与其他相似,但宽度和高度也很重要,你需要一个AdRequest
NativeExpressAdView mNativeExpressAdView = new NativeExpressAdView(this;
mNativeExpressAdView.setLayoutParams(new NativeExpressAdView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 132)); // here 132 is the medium size
mNativeExpressAdView.setAdUnitId("YOUR AD_UNIT ID");
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
//adRequestBuilder.addTestDevice("28776EC697A5120CBA87CB573E26544A"); //if needed
<parent view>.adcontainer.addView(mNativeExpressAdView);
mNativeExpressAdView.loadAd(adRequestBuilder.build());