Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 动态加载子布局时,根布局 padding 为何失效?

編輯:關於 Android 程式設計

先把两个最容易混淆的属性摆清楚。绝大多数 Android 控件都同时拥有 padding 与 layout_margin:

padding——控件内部内容到自身边缘的距离;
margin——控件到其父容器边缘的距离。

做实验时我遇到一个怪现象:动态 inflate 进来的子布局,自身的 padding 和 margin 都按预期生效了,但根布局上写的 padding 却对加进来的子布局毫无约束力。

复现步骤

根布局 activity_main.xml 是一个纵向 LinearLayout,声明了 android:padding="8dp":

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="8dp"
    tools:context=".MainActivity" />

被加载的子布局 table_layout.xml 里放了一个 TextView,它自己带 android:layout_margin="10dp"。

动态加载的代码走的是 addContentView():

LinearLayout subLayout = (LinearLayout) getLayoutInflater()
        .inflate(R.layout.table_layout, null);
TextView tableNameTextView = subLayout.findViewById(R.id.tableLayout_tableName);
tableNameTextView.setText("tablename");
addContentView(subLayout,
        new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

结果:子布局内部那个 10dp 边距正常显示,可 table_layout 整体却紧贴 activity_main 的边缘,根布局的 8dp padding 像是从来没写过。

折腾三小时之后的解法

我试过给根布局和子布局分别设 margin、padding,也试过拆成 top/right/bottom/left 四项单独设置,全都没用。最后奏效的办法却简单得让人无语:在原来的根布局里再套一层布局,把这一层当成新的"根"来加载子布局。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout android:id="@+id/mainLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="8dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp" />
</LinearLayout>
LinearLayout subLayout = (LinearLayout) getLayoutInflater()
        .inflate(R.layout.table_layout, null);
TextView tableNameTextView = subLayout.findViewById(R.id.tableLayout_tableName);
tableNameTextView.setText("tablename");
LinearLayout mainLayout = findViewById(R.id.mainLayout);
mainLayout.addView(subLayout);

为什么会这样

原因不在 padding 本身,而在 addContentView() 的语义。它会把 View 直接挂到 Window 的 android:id/content 容器里,而不是挂到你写的那个 XML 根节点下——你在 activity_main.xml 上设置的 padding,自然管不到一个与它平级、由系统容器承载的 View。

改成 mainLayout.addView(subLayout) 之后,父子关系才真正建立,父容器的 padding 也就顺理成章地生效了。所以说"根布局有特殊限制"其实是个误解:真正的根是系统那个 content 容器,你写的布局从来都不是它的直接子节点。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved