简体   繁体   English

在TOP-CENTER中将内容与RelativeLayout对齐

[英]Align something with RelativeLayout in TOP-CENTER

I'm trying to center the adMob to the top CENTER. 我正在尝试将adMob居中到顶部的CENTER。 I'm in landscape mode. 我处于横向模式。 I decided to keep using BANNER size instead of SMART_BANNER because of the image support in the first one. 由于第一个图像支持,我决定继续使用BANNER大小而不是SMART_BANNER。 It keeps showing in TOP LEFT. 它一直显示在前左。

I need to achieve it without xml files, using java code. 我需要使用Java代码在没有xml文件的情况下实现它。 I'm using RelativeLayout. 我正在使用RelativeLayout。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandle = new Handler() {
            public void handleMessage(Message msg) {
                if ((String) msg.obj == "hide") {
                    adView.setVisibility(View.GONE);
                } else {
                    adView.setVisibility(View.VISIBLE);
                }

            }
        };

        RelativeLayout adsLayout;
        RelativeLayout.LayoutParams lp2;
        Window window;

        window = getWindow();
        adsLayout = new RelativeLayout(this);
        lp2 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        // Displays Ads at the bottom of your sketch, use Gravity.TOP to display
        // them at the top
        adsLayout.setGravity(Gravity.TOP); // TOP, BOTTOM

        adView = new AdView(this);
        adView.setAdUnitId("ca-app-pub-7026369821782045/7333385813");
        adView.setAdSize(AdSize.BANNER);
        adView.setVisibility(View.GONE);

        adsLayout.addView(adView);

        AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice("2BC774A37080BC16DF211A91E61710BA")
        .build();
        adView.loadAd(adRequest);

        window.addContentView(adsLayout, lp2);
    }

    public void hideAds() {
        Message msg = new Message();
        msg.obj = "hide";
        mHandle.sendMessage(msg);
    }

    public void showAds() {
        Message msg = new Message();
        msg.obj = "show";
        mHandle.sendMessage(msg);
    }

use this: 用这个:

lp2 = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp2.addRule(RelativeLayout.CENTER_HORIZONTAL);

Width of the banner will be same as the activity (screen), height will be as tall as it needs to be. 标语的宽度将与活动(屏幕)相同,高度将与需要的高度一样高。

Remove adsLayout.setGravity(Gravity.TOP); 删除 adsLayout.setGravity(Gravity.TOP);

and use lp2 on the adView, instead of the layout. 并在adView而非布局上使用lp2。 adsLayout.addView(adView, lp2);

also, you dont need Window in an Activity, you can use setContentView(adsLayout); 另外,您在Activity中不需要Window ,可以使用setContentView(adsLayout);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM