Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...