通过代码 Android 在其子视图上方对齐父布局

Align parent layout above its child view through code Android

    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 底部对齐,父(main_layout)内容被 AdView 阻止。 我想将 parent(main_layout) 对齐到 adView 上方。有帮助吗?提前致谢。

最简单的方法是使用方向为 'vertical' 的 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>

修复了我的自我。我在 XML 中将父 Relativelayout 更改为垂直方向的 LinearLayout,并将 adView 添加为 LinearLayout 的子项,如下代码所示,然后效果非常好。 (注意XML,给Linearlayout child weight=1 and height=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);

        }
    });