Android:从代码向特定布局添加视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3477581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: Add a view to a specific Layout from code
提问by Erik
I want to dynamically add some views to a LinearLayout
that is already defined in XML.
我想向LinearLayout
已经在 XML 中定义的a 动态添加一些视图。
I'm able to add views to the screen but they are not being placed 'inside' the right LinearLayout
.
我可以向屏幕添加视图,但它们没有被放置在 right 的“内部” LinearLayout
。
How can I get a reference to this specific Layout from code, similar to getting a View
by using findViewById()
?
如何从代码中获取对这个特定布局的引用,类似于View
通过使用获取 a findViewById()
?
回答by Janusz
As Marcarse pointed out you can do
正如马尔卡斯指出的那样,你可以做到
ViewGroup layout = (ViewGroup) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);
The LinearLayout class extends ViewGroupwhich itself extends the View class. This makes acquiring a reference to a layout as easy as getting a reference to another View.
LinearLayout 类扩展了ViewGroup,它本身扩展了 View 类。这使得获取对布局的引用就像获取对另一个视图的引用一样容易。
回答by Macarse
This should work:
这应该有效:
LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);
回答by sumit mehra
Better Version: To add another layout in activity/Fragment
更好的版本:在活动/片段中添加另一个布局
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);
Happy Coding(-:
快乐编码(-: