Android中include的使用


如果在程序中多次用到一部分相同的布局,可以先將這部分布局定義為一個單獨的XML,然后在需要的地方通過<include>引入,如下:

main.xml

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   3: android:layout_width="wrap_content"
   4: android:layout_height="wrap_content">
   5: <include android:layout_width="wrap_content" 
   6: android:layout_height="wrap_content" 
   7: android:id="@+id/cell1" 
   8: layout="@layout/item" 
   9: android:layout_marginTop="10dp" 
  10: android:layout_marginLeft="45dp"/>
  11: <include android:layout_width="wrap_content" 
  12: android:layout_height="wrap_content" 
  13: android:id="@+id/cell2" 
  14: layout="@layout/item" 
  15: android:layout_toRightOf="@+id/cell1"
  16: android:layout_alignTop="@+id/cell1" 
  17: android:layout_marginLeft="20dp"/>
  18: <include android:layout_width="wrap_content" 
  19: android:layout_height="wrap_content" 
  20: android:id="@+id/cell3" 
  21: layout="@layout/item" 
  22: android:layout_toRightOf="@+id/cell2" 
  23: android:layout_alignTop="@+id/cell1" 
  24: android:layout_marginLeft="20dp"/>
  25: </RelativeLayout>

item.xml

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   3: android:layout_width="wrap_content" 
   4: android:layout_height="wrap_content" 
   5: android:visibility="invisible">
   6: <ImageView android:background="#000000" 
   7: android:id="@+id/iv_img" 
   8: android:layout_width="wrap_content" 
   9: android:layout_height="wrap_content" 
  10: android:clickable="true" 
  11: android:focusable="false" />
  12: <TextView android:id="@+id/tv_name" 
  13: android:layout_width="wrap_content" 
  14: android:layout_height="wrap_content" 
  15: android:textColor="#a17006" 
  16: android:textStyle="bold" 
  17: android:textSize="22dp" 
  18: android:layout_alignLeft="@+id/iv_img" 
  19: android:layout_below="@+id/iv_img" />
  20: </RelativeLayout>

使用include時需要注意的是要指定寬高屬性,要不可能會出現一些意想不到的效果,比如引用了三次,而界面上只顯示了一個item


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM