2013-10-02 57 views
0

我想知道如何通過編程方式引用視圖。引用在Android中以編程方式創建的用戶界面元素

我必須創建新的乘客視圖與「添加乘客」和分別「刪除乘客」按鈕到我的應用程序。 Prom Promts保留着名爲「@ + id/passenger」的LinearLayouts,它有兩個名爲「@ + id/passenger_name」和「@ + id/passenger_weight」的EditText。然後,這些被保存在另一個名爲passenger_layout的父級LinearLayout中,可以將所有乘客的LinearLayouts集中在一起

添加新乘客很容易,但我不知道如何引用新創建的元素。我猜他們會自動獲得某種標識符?我更喜歡他們是「passenger_name%」和「passenger_weight%」,其中%是索引_passengerCount。

addPassenger.Click += delegate { 
      //Add to index 
      ++passengerCount; 
      //Prep new passenger layout 
      var newLayout = new LinearLayout(Activity); 
      //Set LayoutParameters from the existing passenger LayoutParameters 
      newLayout.LayoutParameters = newPassenger.LayoutParameters; 

      //Prep the new EditTexts 
      var name = new EditText(Activity); 
      var weight = new EditText(Activity); 

      //Set the EditTexts' LayoutParameters from existing LayoutParameters 
      name.LayoutParameters = new ViewGroup.LayoutParams(passengerName.LayoutParameters); 
      weight.LayoutParameters = new ViewGroup.LayoutParams(passengerWeight.LayoutParameters); 

      //These cleary don't work :< 
//    name.Id = Resources.GetIdentifier("passenger_name" + passengerCount, "id", Activity.PackageName); 
//    weight.Id = "passenger_weight" + passengerCount; 


      //Add EditTexts to the new passenger layout and then and then add the new passenger to the parent LinearLayout 
      newLayout.AddView(name); 
      newLayout.AddView(weight); 
      passengerLayout.AddView(newLayout); 
      Log.Debug(GetType().FullName, "Add clicked"); 
     }; 

這就是我的點擊授人以創建一個新的乘客,但同樣就算我創造他們喜歡這個,我不知道我怎樣才能找到它們,如果我不得不例如刪除或獲取名稱或重量數據。

我該如何參考以編程方式創建的UI元素?

回答

1

在創建視圖時,嘗試給它一些ID,並將該ID作爲某個靜態引用保存。

然後,您可以簡單地調用包含視圖的findViewById(MY_VIEWS_ID)並獲取視圖。

當然,或者,您可以始終在創建代碼時在其代碼中創建的視圖中引用它。如果你害怕內存泄漏,你可以使用WeakReference。

希望這會有所幫助。

0

您可以在Activity中保留一個靜態變量,該變量在初始化後包含UI元素。

喜歡的東西:

// Definition 
private static TextView textViewToSave = null; 

textViewToSave = // create the TextView programatically. 

// Do stuff with the saved TextView 
textViewToSave.setText("O Hai world!"); 
+0

但是我豈不則必須有一堆現成的變量?我猜客運量可能會高達10或15,所以它似乎是一種非傳統的方式來處理它。我想這是一種簡單的方法,目前我可以做到這一點...... – Tibelius

+0

您可以創建一個'HashMap'來代替您的UI元素列表,並且可以保留您需要的任何特殊數據作爲值。或者,如果您需要多個屬性來維護該類並將其初始化爲List或ArrayList,則可以爲其創建一個類。 – Ron

相關問題