Android之根布局动态载入子布局时边距设置无效问题

Android大部分的控件都会有padding和layout_margin两个属性,一般来说它们的差别是:

padding控件中的内容离控件边缘的距离。

margin:  控件离它的父控件边缘的距离。


今天做了一个由根布局动态载入子布局的实验,结果发现子布局中的这两个属性能够按预期的效果显示,可是给根布局设置的padding并没有对被载入的子布局产生效果。


代码例如以下:

根布局文件名称为activity_main.xml,其xml文件定义的内容为:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="8dp"  <!-- 这个布局里控件都距离它的边缘8dp -->
    tools:context=".MainActivity" >

</LinearLayout>


上面这个根布局会加入子布局table_layout.xml中定义的布局,这个xml文件的定义内容是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tableLayout_tableName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"  <!-- 这个控件离table_layout这个布局的边缘为10dp -->
        android:textSize="30sp" />
</LinearLayout>

源代码中实现动态载入的代码段:

// 创建用于承载表的布局
LinearLayout subLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.table_layout, null);
// 填充表名
tableNameTextView = ((TextView) subLayout.findViewById(R.id.tableLayout_tableName));
tableNameTextView.setText("tablename");

this.addContentView(subLayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

可是上面这段代码运行后。table_layout布局里面的边距设置会正常显示。可是activity_main布局中table_layout的边缘却紧紧挨着activity_main的边缘,说明activity_main的padding并没有其效果。


这个问题我纠结了将近3个消失。最终设置了根局部和子布局的margin和padding也不行,分别设置top、right、bottom、left也不行,最终的解决的方法却让我感到很匪夷所思:

仅仅须要在根布局中再加一个布局,把这个布局当做根布局来动态载入子布局就好了。

不知道为什么类型全然同样的根布局就会出错。或许'根'布局有某些特别的限制吧。


改动之后的代码是:

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <!-- 仅仅要这么再加一个布局来取代跟布局就OK了。。

。 --> <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>


源代码:

LinearLayout subLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.table_layout, null);
// 填充表名
tableNameTextView = ((TextView) subLayout.findViewById(R.id.tableLayout_tableName));
tableNameTextView.setText("tablename");

LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);  //通过这个新加的"根布局"来载入子布局
mainLayout.addView(subLayout);



假设转载请注明出处:http://blog.csdn.net/gophers?viewmode=contents


posted on 2019-04-24 17:06  xfgnongmin  阅读(1052)  评论(0编辑  收藏  举报

导航