Getting child elements from LinearLayout

后端 未结 7 1076
北恋
北恋 2020-12-08 09:13

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.

<
相关标签:
7条回答
  • 2020-12-08 09:49

    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
            }
    
    0 讨论(0)
  • 2020-12-08 09:51

    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)
    
    0 讨论(0)
  • 2020-12-08 09:55

    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.

    0 讨论(0)
  • 2020-12-08 09:58

    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

    0 讨论(0)
  • 2020-12-08 10:00
    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;
    }
    
    0 讨论(0)
  • 2020-12-08 10:11

    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
    }
    
    0 讨论(0)
提交回复
热议问题