2015-03-13 45 views
0

如何获取元素并以编程方式多次在同一视图中复制它?
我有这个LinearLayoutRelativeLayout里面,我想克隆我以前写在xml文件中的那个LinearLayout,在RelativeLayout中大约有10次。动态地克隆LinearLayout及其内容在同一个父布局中

这是结构:
enter image description here

这是代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/bg_android" 
    android:weightSum="1"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:layout_margin="10dp" 
     android:id="@+id/relativeLayout"> 

     <ImageView 
      android:layout_width="180dp" 
      android:layout_height="62dp" 
      android:id="@+id/imageView2" 
      android:src="@drawable/cartuxa_logo" 
      android:layout_alignParentTop="true" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" /> 

     <ImageButton 
      android:layout_width="30dp" 
      android:layout_height="30dp" 
      android:id="@+id/menu_btn" 
      android:layout_centerVertical="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:background="@drawable/menu_icon" /> 

    </RelativeLayout> 

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="fill_parent" 
     android:layout_height="230dp" 
     android:gravity="left" 
     android:id="@+id/linearLayout_ID" 
     android:layout_below="@+id/relativeLayout" 
     android:layout_alignLeft="@+id/relativeLayout" 
     android:layout_alignStart="@+id/relativeLayout"> 

     <ImageView 
      android:layout_width="120dp" 
      android:layout_height="120dp" 
      android:id="@+id/ll_preview_ID" 
      android:background="#ff393939" 
      android:layout_marginRight="4dp" /> 

     <ImageView 
      android:layout_width="100dp" 
      android:layout_height="fill_parent" 
      android:id="@+id/ll_image_ID" 
      android:background="#ff767676" 
      android:contentDescription="@string/dfg" /> 


    </LinearLayout> 


</RelativeLayout> 

回答

0

在Eclipse中你可以右键点击你的布局和使用选项提取物包括。 (您也可以手动完成)。它会将您的布局抽取为单独的XML,并使您能够使用<include layout="@layout/yourlayout"/>再次包含新创建的布局。

3

我建议你制作一个单独的布局XML文件,用于您希望在相关布局中添加的文件。 一旦你这样做,你可以以这种方式添加布局

LayoutInflater inflater = (LayoutInflater)getBaseContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
RelativeLayout main =(RelativeLayout)findViewById(R.id.layout1); 

for(int i=0;i<9;i++){ 
View view = inflater.inflate(R.layout.sub_layout, null); 
main.addView(view); 
}