android admob size on dimensions error: A 'typ

2019-09-04 03:18发布

I have a layout and the attribute:

ads:adSize="LARGE_BANNER"

I want to put it with ads:adSize="@dim... dim name"

but it gives me error for example: FULL_BANNER it says something like full banner doesn't exist and it doesn't compile.

I tried it now on styles but it doesn't work too:

<item name="ads:adSize">LEADERBOARD</item>

it says error: A 'type' attribute is required for

any idea?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-04 03:50

You can dynamically load the ad's size based on screen resolution, programatically.

In your activity's class onCreate():

        AdSize adSize = AdSize.SMART_BANNER;

        DisplayMetrics dm = getResources().getDisplayMetrics();

        double density = dm.density * 160;
        double x = Math.pow(dm.widthPixels / density, 2);
        double y = Math.pow(dm.heightPixels / density, 2);
        double screenInches = Math.sqrt(x + y);

        if (screenInches > 8) { // > 728 X 90
            adSize = AdSize.IAB_LEADERBOARD;
        } else if (screenInches > 6) { // > 468 X 60
            adSize = AdSize.IAB_BANNER;
        } else { // > 320 X 50
            adSize = AdSize.BANNER;
        }

        LinearLayout adContainer = (LinearLayout) findViewById(R.id.your_parent_layout);
        adView = new AdView(this, adsize, "xxxxxxxxxx");
        AdRequest adRequest = new AdRequest();
        adView.loadAd(adRequest);

        // Place the ad view.
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        adContainer.addView(adView, params);

If you prefer defining the adview in xml format and referencing the values from the values-sw600, values-sw720.. folders you can define the width and height in dimens.xml:

In values/dimens.xml

  <resources>
        <!-- Default screen margins, per the Android Design guidelines. -->
        <dimen name="admob_width">320dp</dimen>
        <dimen name="admob_height">50dp</dimen>
    </resources>

Then, in your layout:

<com.google.ads.AdView 
    android:id="@+id/adView"
    android:layout_width="@dimen/admob_width"
    android:layout_height="@dimen/admob_height"
    ads:adUnitId="your_unit_id"
    ads:adSize="SMART_BANNER"
    ads:loadAdOnCreate="true"/>
查看更多
登录 后发表回答