I have seen some widgets using addView and sometimes addViewInLayout.
What is the difference between them? What will happen if I replace one with the other?
Should I keep a flag during layout and use "addViewInLayout" or "addView" accordingly?
Thanks.
BR, Henry
ps. add more tags: removeview, removeviewinlayout
Its generally a bad idea to call addView
inside onLayout
because addView
internally triggers a requestLayout
which eventually will call onLayout
. So you end up triggering a layout while you are in the middle of a layout.
addViewInLayout
is a "safer" version of the addView
in the case you really have to add a new view in onLayout
. It basically doesn't trigger a layout pass (doesn't call requestLayout internally).
See this video (by android engineer) for more detail: http://www.youtube.com/watch?v=HbAeTGoKG6k
addViewInLayout
Adds a view during layout. This is useful if in your onLayout() method, you need to add more views (as does the list view for example). If index is negative, it means put it at the end of the list.
addView
Assign the passed LayoutParams to the passed View and add the view to the window.
*Note that addView is implemented by ViewManager
, an Interface to let you add and remove child views to an Activity, so you will be able to add views to ViewGroup at run time (DYNAMICALLY). Also note that addViewInLayout is a protected method of ViewGroup so if you are doing to create a custom view group you can call addViewInLayout()
in onLayout()
method.
For more see this
for example: we have a Layout (mLayout) and you want to add 2 views (view1, view2) into this layout.so there are 2 ways (the same)
case1: simply you use following command
mLayout.addView(view1); //onLayout() will be called first time
mLayout.addView(view2); //onLayout() will be called second time after the first time.
in this case, you don't care function onLayout(). it is simple source code.
case2: complicate but better performance
//do something to <global variable>
bCheck = true; //check it in fuction onLayout()
requestLayout(); //use this function to call onLayout() function for only one time
//in onLayout() function of mLayout, you use addViewInLayout()
//addViewInLayout() dont call onLayout() function, so you can add 2 views with only one time to call onLayout()
//onLayout() is abstract function, so mLayout is a instant of subclass of ViewGroup (ex: RelativeLayout, LinearLayout....)
@Override
onLayout(boolean changed, int l, int t, int r, int b)
if(bCheck == true){
v.addViewInLayout(view1); //add view1 to mLayout
v.addViewInLayout(view1); //add view2 to mLayout
bCheck = false;
}
}
});
I have no time to test it. anyone can help me make it more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With