[android] Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

I've had severe trouble getting LayoutInflater to work as expected, and so did other people: How to use layoutinflator to add views at runtime?.

Why does LayoutInflater ignore the layout parameters I've specified? E.g. why are the layout_width and layout_height values from my resources XML not honored?

This question is related to android android-layout

The answer is


andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/


wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok