2011-07-07 17 views
36

से बाल तत्व प्राप्त करना क्या LinearLayout के बच्चे तत्व को प्राप्त करने का कोई तरीका है? मेरा कोड एक दृश्य (लाइनरलेआउट) देता है, लेकिन मुझे लेआउट के अंदर विशिष्ट तत्वों तक पहुंच प्राप्त करने की आवश्यकता है।LinearLayout

कोई सुझाव?

(हाँ, मैं मैं findViewById इस्तेमाल कर सकते हैं पता है, लेकिन मैं लेआउट जावा में/बच्चों बनाने रहा हूँ - नहीं एक्सएमएल।)

उत्तर

66

तुम हमेशा कुछ इस तरह कर सकते हैं:

LinearLayout layout = setupLayout(); 
int count = layout.getChildCount(); 
View v = null; 
for(int i=0; i<count; i++) { 
    v = layout.getChildAt(i); 
    //do something with your child element 
} 
+10

धन्यवाद करने के लिए डाली। क्या काम किया गया था: 'टेक्स्ट व्यू टीवी = (टेक्स्ट व्यू) ((लीनियरलाउट) v) .getChildAt (0); ' – Cody

16

मुझे लगता है कि इस मदद कर सकता है: हर करने के लिए टैग findViewWithTag()

सेट टैग के लिए लेआउट में जोड़ने के लिए देखते हैं और फिर पाने कि दृश्य के रूप में आप आईडी

का उपयोग करते हैं
3

मैं avoi हैं डी दृष्टि से बच्चों के दृष्टिकोण से एक तत्व हथियाने। यह अब काम कर सकता है, लेकिन कोड को बनाए रखने में मुश्किल बनाता है और भावी रिलीज को तोड़ने के लिए अतिसंवेदनशील बनाता है। जैसा कि ऊपर बताया गया है, टैग को सेट करना और टैग द्वारा दृश्य प्राप्त करना उचित तरीका है।

1

आप ऐसा कर सकते हैं।

ViewGroup layoutCont= (ViewGroup) findViewById(R.id.linearLayout); 
getAllChildElements(layoutCont); 
public static final void getAllChildElements(ViewGroup layoutCont) { 
    if (layoutCont == null) return; 

    final int mCount = layoutCont.getChildCount(); 

    // Loop through all of the children. 
    for (int i = 0; i < mCount; ++i) { 
     final View mChild = layoutCont.getChildAt(i); 

     if (mChild instanceof ViewGroup) { 
      // Recursively attempt another ViewGroup. 
      setAppFont((ViewGroup) mChild, mFont); 
     } else { 
      // Set the font if it is a TextView. 

     } 
    } 
} 
1
LinearLayout layout = (LinearLayout)findViewById([whatever]); 
for(int i=0;i<layout.getChildCount();i++) 
    { 
     Button b = (Button)layout.getChildAt(i) 
    } 

वे सभी बटन रखते हैं, अन्यथा देख सकते हैं और वर्ग के लिए जाँच

View v = (View)layout.getChildAt(i); 
if (v instanceof Button) { 
    Button b = (Button) v; 
} 
संबंधित मुद्दे