[英]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底部對齊,因此parent(main_layout)內容會被AdView阻止。 我想將adView上方的parent(main_layout)對齊。 有什么幫助嗎? 提前致謝。
最簡單的方法是使用“垂直”方向的LinearLayout,其中@ + id / main_layout_1st_screen位於第一個,而AdView位於第二個。
您為什么要在代碼中執行此操作? 只需在布局xml中定義AdView也很容易(用您的RelativeLayout替換我的web視圖):
<?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>
修正了我的自我。 我將父級Relativelayout更改為在XML中具有垂直方向的LinearLayout,並將adView作為LinearLayout的子級添加,如下代碼所示,然后效果很棒。 (在XML中請注意,為Linearlayout子項賦予weight = 1和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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.