What is the use of “attach to root” in layout inflater?

前端 未结 4 862
春和景丽
春和景丽 2020-12-28 15:11

I am a newbie to android, I know this question has already been asked but i couldn\'t get a satisfactory explanation. My doubts are:

  1. What is \"attach to root\"
相关标签:
4条回答
  • 2020-12-28 15:49

    I myself was also confused about what was the real purpose of attachToRoot in inflate method. After a bit of UI study, I finally got the answer:

    parent:

    in this case is the widget/layout that is surrounding the view objects that you want to inflate using findViewById().

    attachToRoot:

    attaches the views to their parent (includes them in the parent hierarchy), so any touch event that the views recieve will also be transfered to parent view. Now it's upto the parent whether it wants to entertain those events or ignore them. if set to false, they are not added as direct children of the parent and the parent doesn't recieve any touch events from the views.

    Hope this clears the confusion

    0 讨论(0)
  • 2020-12-28 15:49

    For example :

    ChildView : TextView

    Parent(Container)View : LinearLayout

    if attach to root = true

    val view = layoutInflater.inflate(R.layout.child, containerView, true)
    // Not need  -> containerView.addView(view) 
    // This view will be LinearLayout. Not Textview. 
    

    if attach to root = false

    val view = layoutInflater.inflate(R.layout.child, containerView, false)
    containerView.addView(view) // we should add
    // This view will be TextView. 
    
    0 讨论(0)
  • 2020-12-28 16:14

    The third parameter in the inflate method is of boolean return type.
    There is a lot of confusion(Will get to this part soon) when it comes to choose the value of the parameter.

    Its Simple
    1) When attachToRoot = false it means

    Dont attach the child view to parent "Right Now", Add it later.

    2) When attachToRoot = true it means

    Attach the childView to parent "Right Now".

    In both cases the child view will be added to parentView eventually. Its just the matter of time.
    If you want to read in more details you can refer --->>> this answer
    (Because i can not post duplicate answer here, Just want to help).

    0 讨论(0)
  • 2020-12-28 16:14

    If you pass a ViewGroup to it, it will add the inflated View to that ViewGroup. That means, the inflated View will be a child of the passed ViewGroup.

    It is irrelevant whether the ViewGroup is made programatically or by an xml file.

    0 讨论(0)
提交回复
热议问题