Android在layout xml中使用include完成靜態載入,androidlayout

來源:互聯網
上載者:User

Android在layout xml中使用include完成靜態載入,androidlayout
 Android在layout xml中使用include完成靜態載入

include靜態載入:
不僅可以載入布局,還可以載入控制項(控制項標籤名要在最外層)
include標籤中有個layout屬性就是專門用來載入的。

 

在Android的layout樣式定義中,可以使用xml檔案方便的實現,有時候為了模組的複用,使用include標籤可以達到此目的。例如:

<include layout="@layout/otherlayout"></div> 

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="fill_parent"    android:layout_height="wrap_content" >    <Textview        android:layout_width="fill_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="fill_parent"    android:layout_height="wrap_content"    android:layout_below="@id/top" >    <include layout="@layout/otherlayout"></Linearlayout > 

在Statckoverflow上找到了更好的解決方案: 解答道:必須同時重載layoutwidth和layoutheight屬性,其他的layout_*屬性才會起作用,否這都會被忽略掉。上面的例子應該寫成這樣:

<include layout="@layout/otherlayout">    android:layout_height="wrap_content"    android:layout_width="fill_parent"    android:layout_below="@id/top" />

另外,關於xml的複用,還可以使用merge標籤,merge標籤主要是用來最佳化顯示的,減少View樹的層級,可以參考這裡:https://developer.android.com/resources/articles/layout-tricks-merge.html, 翻譯版在這裡:http://apps.hi.baidu.com/share/detail/20871363

 原文:http://www.race604.com/using-include-in-layout/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.