【问题标题】:Align something with RelativeLayout in TOP-CENTER将某些内容与 TOP-CENTER 中的 RelativeLayout 对齐
【发布时间】:2013-11-29 05:12:14
【问题描述】:

我正在尝试将 adMob 置于顶部 CENTER 的中心。我在横向模式。由于第一个中的图像支持,我决定继续使用 BANNER 大小而不是 SMART_BANNER。它一直显示在左上角。

我需要在没有 xml 文件的情况下使用 java 代码来实现它。我正在使用相对布局。

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);
    }

【问题讨论】:

    标签: android alignment android-relativelayout


    【解决方案1】:

    使用这个:

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

    横幅的宽度将与活动(屏幕)相同,高度将尽可能高。

    删除 adsLayout.setGravity(Gravity.TOP);

    并在 adView 上使用 lp2,而不是布局。 adsLayout.addView(adView, lp2);

    另外,Activity 中不需要Window,可以使用setContentView(adsLayout);

    【讨论】:

    • 爱你,伙计。有效。我需要 Window,因为它需要重叠一些东西。
    • 很高兴为您提供帮助。如果这解决了您的问题,请考虑接受作为答案。
    • lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP); 为我解决了问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2014-10-03
    • 2018-07-07
    相关资源
    最近更新 更多