简体   繁体   中英

Getting child elements from LinearLayout

Is there a way to obtain a child element of a LinearLayout? My code returns a view (linearlayout), but I need to get access to specific elements inside of the layout.

Any suggestions?

(Yes, I know I could use findViewById, but I am creating the layouts/children in java - not XML.)

You can always do something like this:

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
}

I think this could help: findViewWithTag()

Set TAG to every View you add to the layout and then get that View by the TAG as you would do using ID

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

If they are all buttons, otherwise cast to view and check for class

View v =  (View)layout.getChildAt(i);
if (v instanceof Button) {
     Button b = (Button) v;
}

I would avoid statically grabbing an element from the view's children. It might work now, but makes the code difficult to maintain and susceptible to breaking on future releases. As stated above the proper way to do that is to set the tag and to get the view by the tag.

You can do like this.

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.

        }
    }
}

One of the very direct ways is to access the child views with their ids.

view.findViewById(R.id.ID_OF_THE_CHILD_VIEW)

here view is the parent view.

So for instance your child view is an imageview, with id, img_profile, what you can do is:

ImageView imgProfile = view.findViewById(R.id.img_profile)

The solution in Kotlin version will be:

val layout: LinearLayout = setupLayout()
        val count = layout.childCount
        var v: View? = null
        for (i in 0 until count) {
            v = layout.getChildAt(i)
            //do something with your child element
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM