通过代码Android将父级布局与其子视图对齐

时间:2015-03-04 09:43:54

标签: android android-layout

    main_layout = (RelativeLayout) findViewById(R.id.main_layout_1st_screen);
    AdView adView = new AdView(this);
    adView.setAdUnitId("AD_ID");
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setId(660022451);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    adView.setLayoutParams(params);
    main_layout.addView(adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    adView.setAdListener(new AdListener() {
        public void onAdLoaded() {

        }
    });

上面的代码工作正常,但由于adView在底部对齐,因此AdView会阻止父(main_layout)内容。 我想将父(main_layout)与adView对齐。任何帮助?提前谢谢。

2 个答案:

答案 0 :(得分:1)

最简单的方法是使LinearLayout具有方向'垂直'其中@ + id / main_layout_1st_screen是第一个,而您的AdView是第二个。

你为什么要在代码中这样做?在布局xml中定义AdView也很容易(用您的RelativeLayout替换我的webview):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff000000">

    <RelativeLayout
        android:id="@+id/main_layout_1st_screen"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_width="fill_parent">

    </RelativeLayout>


    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"

        android:id="@+id/about_ad"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        ads:adSize="@string/adsize"
        ads:adUnitId="@string/admobid"/>
</LinearLayout>

答案 1 :(得分:0)

修正了我的自我。我使用XML中的垂直方向将父Relativelayout更改为LinearLayout,并将adView添加为LinearLayout的子项,如下面的代码,然后它工作得很棒。 (注意,在XML中,给出Linearlayout子权重= 1和高度= 0dp)

    main_layout = (LinearLayout) findViewById(R.id.main_layout_1st_screen);
    final AdView adView = new AdView(this);
    adView.setAdUnitId("AdID");
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setId(660022451);
    final LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    adView.setAdListener(new AdListener() {
        public void onAdLoaded() {
            main_layout.addView(adView, param);

        }
    });