2016-02-08 248 views
0

我的项目文件有XML,如根xml。在根xml我限定Relative layout像下面如何在相对布局中动态添加相对布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/root_view"> 
    </RelativeLayout> 

我有另一个xml文件首先是one.xml和另一个是two.xml像下面

one.xml

 <?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:visibility="gone" 
     android:id="@+id/two_video_layout"> 

      <TextView 
        android:id="@+id/two_video_title" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dp" 
        android:singleLine="true" 
        android:text="Video Title" /> 


</RelativeLayout> 

和另一个布局是

two.xml

<?xml version="1.0" encoding="utf-8"?> 
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:visibility="gone" 
      android:id="@+id/two_video_layout"> 

       <Imageview 
         android:id="@+id/image" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         /> 


    </RelativeLayout> 

,我们怎样才能root.xml添加one.xmltwo.xml动态与某些条件,以及如何可以访问one.xml文件

回答

1

的TextView的引用您必须添加使用的LayoutParams的看法。

LinearLayout linearLayout = new LinearLayout(this); 

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
     LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); 

    parentView.addView(linearLayout, relativeParams); 

要以相对方式以编程方式定位您的物品,您必须为其分配ID。

TextView tv1 = new TextView(this); 
tv1.setId(1); 
0

尝试这样的事情, 其中rootLayout是的ROOT.xml

RelativeLayout two_video_layout=new RelativeLayout(this); 
rootLayout.addView(two_video_layout); 
0

您可以使用LayoutInflater这样的:

LayoutInflater inflater=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.viewYou_want_to_inflate, null); 
// to inflate one.xml call 
View v = inflater.inflate(R.layout.one, null); 
TextView textView=(TextView)v.findViewById(R.id.two_video_title); // to get textview object from one.xml 
// to inflate two.xml call 
View v = inflater.inflate(R.layout.two, null); 

,并在根视图中添加视图请拨打addView这样的功能:

RelativeLayout root_layout=(RelativeLayout)findViewById(R.id.root_view); 
layout.addView(v);