我刚开始使用android开发并遇到一个问题我无法找到任何信息。我使用双窗格模板创建了一个项目。在双窗格模式(activity_setting_twopane.xml)中,我能够为我的应用添加AdView
和许多其他视图。我挣扎的是如何将视图(任何)添加到较小显示的其他布局(activity_setting_detail.xml,activity_setting_list.xml或fragment_setting_detail.xml?)。我能够将一个视图(AdView
)添加到fragment_setting_detail.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/setting_list"
android:name="com.test.firstapp.SettingListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context=".SettingListActivity"
tools:layout="@android:layout/list_content" >
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxx" >
</com.google.android.gms.ads.AdView>
</fragment>
我认为这不是正确的方法,而是唯一可行的方法。但AdView
显示在屏幕顶部,我不知道如何定位它,因为在Fragments
中大多数参数都不允许使用。我甚至尝试将其包装在LinearLayout
中,但随后示例项目崩溃,我想在视图中将视图添加到布局中。将任何视图添加到基于xml的Fragments
的正确方法是什么(使用我理解的示例)?许多事先提前
答案 0 :(得分:1)
正确的方法:
<!-- assign a layout_gravity to your Views -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SettingListActivity"
tools:layout="@android:layout/list_content"
android:orientation="vertical" >
<fragment
android:id="@+id/setting_list"
android:name="com.test.firstapp.SettingListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" />
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="480dp"
android:layout_height="75dp"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxx"
android:layout_gravity="bottom" />
</LinearLayout>
注意:强>
不要混淆android:gravity
和android:layout_gravity
。
android:gravity
&gt;为“孩子”分配重力
android:layout_gravity
&gt;将重力分配给“父母”。
有关详细信息,请参阅此答案:Android - gravity and layout_gravity
修改强>
仅供参考:ViewGroup
是:
“可以包含其他视图的特殊视图(称为子视图)。视图组是布局和视图容器的基类。”参考:ViewGroup Android Developer Documentation
您的fragment
不能是AdView
的父级,您需要“父级视图”为LinearLayout
,RelativeLayout
,AbsoluteLayout
(已弃用),{ {1}}等等。
您的TableLayout
失败了,因为您必须为其指定宽度/高度值,如下所示:AdView failed to instantiate。另请阅读:com.google.ads.AdView failed to instantiate
希望这有帮助。