2012-06-01 45 views
3

是否有可能獲得匹配特定標籤的清單或找到所有Spinner找到所有匹配標籤的紡紗廠

我希望用戶能夠即時添加新的Spinner小部件,但我需要能夠動態地從每個Spinner獲取值。

jQuery中,我可以選擇與$('.myClassSelector').each()相匹配的所有元素。這可以,或類似的,可以在Android中完成嗎?

UPDATE 所有紡紗器都在特定的LinearLayout中,這是在XML中指定的。佈局被用作所有紡紗器的容器。

+0

走的主要佈局樹尋找紡紗廠。 –

+0

你能否提供一些關於你的需求的更多信息?就像我們可以將所有微調器添加到xml中已存在的相同線性佈局中,或者我們需要按照需求將它們添加到不同的佈局中。 –

+0

更新了帖子;它們都被添加到XML中指定的'LinearLayout'中。 – Cody

回答

3

我認爲你可以得到你之前添加Spinner的佈局的所有孩子,並檢查孩子是否是Spinner

LinearLayout ll = //Your Layout this can be any Linear or Relative layout 
        //in which you added your spinners at runtime ; 

    int count = ll.getChildCount(); 
    for(int i =0;i<count;i++) 
    { 
     View v = ll.getChildAt(i); 
     if(v instanceof Spinner) 
     { 
      // you got the spinner 
      Spinner s = (Spinner) v; 
      Log.i("Item selected",s.getSelectedItem().toString()); 
     } 
    } 
1

如果可能的話會更好,添加所有紡紗廠在相同的線性佈局和使用FasteKerinns解決方案,但是當且僅當無法嘗試像下面的一些東西.....

Vector spinners = new Vector(): 

private void treverseGroup(ViewGroup vg) 
{ 
    final int count = vg.getChildCount(); 
    for (int i = 0; i < count; ++i) 
    { 
     if (vg.getChildAt(i) instanceof Spinner) 
     { 

      spinners.add(vg.getChildAt(i)); 
     } 
     else if (vg.getChildAt(i) instanceof ViewGroup) 
      recurseGroup((ViewGroup) gp.getChildAt(i)); 
    } 

} 
+0

傳遞根視圖........ –

0

下面的方法能夠在不使用遞歸的情況下檢索整個視圖層次結構中的所有Spinner,其根源爲root。它也匹配給定的標籤。

private ArrayList<Spinner> getSpinners(ViewGroup root, Object matchingTag) { 
    ArrayList<?> list = root.getTouchables(); 

    Iterator<?> it = list.iterator(); 
    while (it.hasNext()) { 
     View view = (View) it.next(); 
     if (!(view instanceof Spinner && view.getTag().equals(matchingTag))) { 
      it.remove(); 
     } 
    } 

    return (ArrayList<Spinner>) list; 
} 
+0

這很有趣,我剛剛在我的項目中編寫了這個方法來獲取所有'EditText's。 –

+0

您可能想在調用equals()之前檢查getTag()的返回值爲null。 –

+0

爲什麼不可能爲textview做同樣的事情。是不是可觸摸的textt視圖然後它叫什麼? – 2015-02-16 09:08:38