当前位置:操作系统 > 安卓/Android >>

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

 

摘自  源代码
 
 
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,