There is already a question here with title Making sense of LayoutInflater, which has very good explanation by @andig which is accepted. But one thing bothering me is a behavior of addView when no parent is specified during inflating and no height/width is specified in addView. Below is code posted with explanation by @andig:-
Main layout (main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Child layout (red.xml)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="25dp"
android:layout_height="25dp"
android:background="#ff0000"
android:text="red" />
Activity code with layoutinflator
public class InflaterTest extends Activity {
private View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
// result: layout_height=wrap_content layout_width=match_parent
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view);
// result: layout_height=100 layout_width=100
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view, 100, 100);
// result: layout_height=25dp layout_width=25dp
// view=textView due to attachRoot=false
view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
parent.addView(view);
// result: layout_height=25dp layout_width=25dp
// parent.addView not necessary as this is already done by attachRoot=true
// view=root due to parent supplied as hierarchy root and attachRoot=true
view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
}
}
Case bothering is code entered below comment // result: layout_height=wrap_content layout_width=match_parent. I checked the code and found that as parent is not specified during inflating, child layout params are ignored and by explanation it should take of the parent/root to which this child layout will be added to.
But when i execute and run this code, in spite of parent/root (main.xml) layout_height specified is match_parent, layout_height considered was wrap_content, but width was considered correctly i.e. match_parent.
I ran this on device with android os 4.0.4.
So question is, is this some kind of bug or it is something that when you don't specify any layout param and root while inflating layout_height considered is wrap_content.