【问题标题】:A lot of spacing between views and margin doesn't do the stuff视图和边距之间的大量间距不起作用
【发布时间】:2017-10-27 09:18:54
【问题描述】:

我有一个带有垂直 LinearLayout 的 Horizo​​ntalScrollView。在那里我添加了一些相同类型的自定义视图。默认情况下,视图之间有很多间距。所以我猜我必须将视图的边距设置为 0 或其他东西。但绝对没有结果。
首先,我尝试更改 xml 中的边距

    <gui.CardUi
     android:id="@+id/cardUi"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"
     android:layout_margin="0dp"
   </gui.CardUi>

比我尝试更改代码中的边距:

    private void setMargins ( int left, int top, int right, int bottom) {
     if (getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) getLayoutParams();
        p.setMargins(left, top, right, bottom);
        requestLayout();
     }
    }

 setMargins(0, 0, 0, 0);

不确定信息是否重要,但我使用 LayoutInflater 以编程方式添加视图。

【问题讨论】:

    标签: android layout android-linearlayout margin


    【解决方案1】:

    由于您膨胀视图的方式,您的边距不会被设置。 我猜你是这样用的:

    View child = getLayoutInflater().inflate(R.layout.mylayout, null);
    

    关键是当您想要充气视图并将其添加到另一个视图时,您应该通知充气器有关容器视图的信息(在您的示例线性布局中)。因此,您的布局参数(例如边距、重量和重力)将被正确设置。 所以改用这个方法:

    View child = getLayoutInflater().inflate(R.layout.child, item, false);
    

    无需在代码中添加边距。

    【讨论】: