2017-07-31 78 views
1

主要目標是使用預先製作的佈局創建可編輯的單獨模塊,然後以編程方式將它們添加到根佈局。爲了澄清,several modules stuck together would look like this.我想動態創建由名稱,日期和字母組成的每個可點擊的塊。將各塊的.axml代碼如下:有沒有辦法以編程方式在android中創建佈局的副本?

 <RelativeLayout 
      android:minWidth="25px" 
      android:minHeight="25px" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/borderLayout" 
      android:background="@drawable/line" 
      android:paddingBottom="1dp" 
      android:paddingTop="1dp"> 
      <RelativeLayout 
       android:id="@+id/relativeLayout1" 
       android:padding="10dp" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:clickable="true" 
       android:background="#ff2f2f2f"> 
       <TextView 
        android:text="C" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/textView1" 
        android:layout_alignParentLeft="true" 
        android:textSize="30dp" /> 
       <TextView 
        android:text="Washington" 
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_toRightOf="@id/textView1" 
        android:id="@+id/textView2" 
        android:layout_alignParentRight="true" 
        android:gravity="right" /> 
       <TextView 
        android:text="6-8-17" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_below="@id/textView2" 
        android:id="@+id/textView3" 
        android:gravity="right" 
        android:layout_alignParentRight="true" /> 
      </RelativeLayout> 
     </RelativeLayout> 

我有在我格式化他們在.axml文件的方式編程格式的意見的主要問題。

回答

1

假設您有一個LinearLayout在你的主axml你希望連接多個視圖的vertical的方向。

獲取對「父」 LinearLayout一個參考:在一些循環

var linearLayoutParent = FindViewById<LinearLayout>(Resource.Id.linearLayout1); 

然後,使用LayoutInflater.Inflate誇大你的重複佈局,使用視圖返回和FindViewByIdView每個元素的需要更新,然後該視圖添加到父視圖隨着增加的索引:

index++; 
var view = LayoutInflater.Inflate(Resource.Layout.RepeatingLayout, linearLayoutParent, false); 
var letter = view.FindViewById<TextView>(Resource.Id.textView1); 
letter.Text = index.ToString(); 
// FindViewById for textView2, textView3 and assign the text on each.... 
linearLayoutParent.AddView(view, index); 

enter image description here

注意:如果您有很多這些重複元素,並且您將不得不滾動它們(不在屏幕上),請使用RecyclerView來代替,它將爲您節省很多頭痛的內存管理,滾動性能等方面的問題。 ... ;-)

+0

謝謝,這真的很有幫助! –

2

使用inflater從資源創建視圖。然後,你可以將其添加編程

context.LayoutInflater.Inflate(Resource.Layout.oneimg_twolbl, null); 
相關問題