我想知道,如果仅提供LinearLayout的单层作为ListView的行 View ,其边距将被忽略。

如果使用ListView的行 View ,则边距将被忽略

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="5dp"

但是,如果我提供LinearLayout的双层结构,而第一层充当“虚拟”层,则其边距将不会被忽略。

我们将在ListView的行 View 中有 margin
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/buyPortfolioLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="5dp"

我可以知道为什么会这样吗?

最佳答案

事实是,LinearLayout(子级)的边距要求其父级布局(容器)给x值给子级布局一个余量。

因此,如果父级布局的LayoutParams支持页边距,则该页边距将得到遵守并应用。
ListView默认使用 AbsListView.LayoutParams ,它不包括任何边距支持,仅包括高度和宽度,这就是为什么,它只是忽略了边距的params值。

而其他布局参数(例如 ActionBar.LayoutParams FrameLayout.LayoutParams GridLayout.LayoutParams LinearLayout.LayoutParams RelativeLayout.LayoutParams )是ViewGroup.MarginLayoutParams的子级,它尊重子级的边距值。

07-28 02:30
查看更多