Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use layoutinflator to add views at runtime?

I have two layouts: main.xml and buttonpanel.xml. In buttonpanel.xml, in main linearlayout I set gravity to bottom. Now i am trying to add the buttonpanel layout using the following code.

setContentView(R.layout.main);
LinearLayout layout=(LinearLayout)findViewById(R.id.mainlinearlayout);
LayoutInflater inflater= (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.buttonpanel,null);
layout.addView(view);

My problem is that the panel is added to the top though i have set gravity to bottom in buttonpanel.xml. If I add buttonpanel.xml to main.xml using include it works fine.

Can anyone help me what is the wrong with my code?

like image 856
Hitendra Avatar asked Jan 19 '11 13:01

Hitendra


People also ask

What's the purpose of LayoutInflater?

LayoutInflater is used to create a new View (or Layout ) object from one of your xml layouts. findViewById just gives you a reference to a view than has already been created.

What is an inflator What does it mean to inflate a view can you add views to a layout using Java code?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

How do I get LayoutInflater from context?

Use getLayoutInflater() to get the LayoutInflater instead of calling LayoutInflater. from(Context).


1 Answers

I have had problems with layout parameters being dropped when inflating views in the way that you are doing it. If I use a slightly different call to inflate my layout parameters are respected:

parent_view = inflater.inflate(R.layout.buttonpanel, parent);

Or in my case, when the parent did not support adding views to it:

view = inflater.inflate(R.layout.buttonpanel, parent, false);

Perhaps this will solve your problem as well.

EDIT: Different views are returned depending on what parameters are given. LayoutInflater

like image 135
Arlaharen Avatar answered Oct 27 '22 08:10

Arlaharen