【发布时间】:2013-11-01 13:33:48
【问题描述】:
我正在创建包含LinearLayout 的动态视图,并将它们添加到外部LinearLayout。我想在创建的视图周围设置一个边距,但 XML 文件中的 layout_margin 被忽略。如果我在代码中设置参数,它可以工作,但我想在布局 XML 中指定边距。
在 XML 布局中设置边距将被忽略:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical" >
...
</LinearLayout>
允许在创建时设置边距:
LinearLayout productView = (LinearLayout) getLayoutInflater().inflate(R.layout.product_preview, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50, 50, 50, 50);
productView.setLayoutParams(params);
这是外部布局。视图被添加到dealer_activity_product_list。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/dealer_activity_dealer_image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="@string/dealer_activity_dealer_image_desc" />
<TextView
android:id="@+id/dealer_activity_dealer_address"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/dealer_activity_product_list1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/dealer_activity_product_list2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" />
</LinearLayout>
</LinearLayout>
【问题讨论】:
-
您是否尝试过使用 Hierarchy 查看器?或尝试将视图转储到 uiautomator?使用这些工具,您可以检查您的布局。您可以发布您正在使用的完整代码吗?
-
能否请您发布更多代码?喜欢完整的 XML?我认为您将边距设置为错误的项目
-
我使用 HierachyViewer 检查布局。虽然在代码中设置边距反映在布局的属性中,但我找不到 XML 文件中设置的值。
-
我在问题中添加了外部布局...
-
我遇到了同样的问题,如果我在 xml 文件中添加带有边距的布局之外的父线性布局,它可以工作。 Eclipse 声称额外的线性布局没用,但它确实有效。
标签: android layout android-linearlayout margin