Android使用include标签无法设置具体位置的解决

一、简介:

Android的layout样式定义中,可以使用xml文件方便的实现,有时候为了模块的复用,使用include标签可以达到此目的。例如:

<include layout="@layout/otherlayout"/> 
二、Android开发的官方网站的说明在这里。其中,有提到:

Similarly, you can override all the layout parameters. This means that any android:layout_ attribute can be used with the <include>tag.*

也就是说是任何android:layout_*属性都可以应用在标签中。
如果使用如下代码:

<Relativelayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <Textview
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/somestring"
        android:id="@+id/top" />

    <include layout="@layout/otherlayout"
        android:layout_below="@id/top" />
</Relativelayout > 

结果我发现include的otherlayout,并没有在如我们预期的在id/top这个TextView下面,而是忽略了android:layout_below属性。经过Google发现,很多人遇到类似的问题。

三、

他们的解决方法是在include的外面再包一层LinearLayout,如下:

<Linearlayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_below="@id/top" >

     <include layout="@layout/otherlayout">

</Linearlayout > 
四、最终的解决办法

结果上Statckoverflow找到了更好的解决方法(http://stackoverflow.com/questions/2316465/how-to-get-relativelayout-working-with-merge-and-include):
解答道:必须同时重载layout_width和layoutheight熟悉,其他的layout属性才会起作用,否这都会被忽略掉。*
所以上面的例子应该写成这样:

<include 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      layout="@layout/otherlayout"
      android:layout_below="@id/top" />
    原文作者:唠嗑008
    原文地址: https://www.jianshu.com/p/40b0445477e9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞