Typical Error cases:
Often we will dynamically add some sub-layouts, such as the following code, through the AddView method.
LinearLayout linparent = (linearlayout) Findviewbyid (r.id.aty_slider_linparent);
View vchild = minflater.inflate (r.layout.view_loding, NULL);
Linparent.addview (Vchild);
View_loading is a layout file:
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:gravity= "Center"
android:orientation= "Horizontal" >
</LinearLayout>
The layout control that view_loding belongs to is completely filled with linparent, but the actual effect is different from the expected, just the adaptive size.
Cause Analysis:
See the source code for the AddView method as follows
public void AddView (View child) {
AddView (Child,-1);
}
Then look at another overloaded method for AddView
public void AddView (View child, int index) {
Layoutparams params = Child.getlayoutparams ();
if (params = = null) {
params = Generatedefaultlayoutparams ();
if (params = = null) {
throw new IllegalArgumentException ("Generatedefaultlayoutparams () cannot return null");
}
}
AddView (Child, index, params);
}
There is a sentence child.getlayoutparams (), and the Getlayoutparams method description has the following words: This method may return null if the this View is not attached to a paren T ViewGroup. This means that if it is not added to the parent control, the result is null, and it is clear that Vchild has not been added to the linparent in the current code trace, so it will call the Generatedefaultlayoutparams () method, The Generatedefaultlayoutparams method is implemented as follows:
Protected Layoutparams Generatedefaultlayoutparams () {
return new Layoutparams (Layoutparams.wrap_content, layoutparams.wrap_content);
}
Therefore, it is obvious that the sub-layout android:layout_width= "Match_parent" property is invalid.
Solution:
When the AddView method is complete, reset the Layoutparams property of the child control Vchild.
Vchild.setlayoutparams (New Android.widget.LinearLayout.LayoutParams (
Android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
Android.widget.LinearLayout.LayoutParams.MATCH_PARENT));
The Layoutparams class must be of type linparent, otherwise there will be bugs.