2016-02-08 217 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);