Android:从代码中将视图添加到特定布局

Android:从代码中将视图添加到特定布局,android,layout,Android,Layout,我想动态地将一些视图添加到已在XML中定义的LinearLayout 我可以将视图添加到屏幕中,但它们没有被“放在”右侧的LinearLayout 如何从代码中获取此特定布局的引用,类似于使用findViewById()获取视图?这应该可以: LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id); TextView tv = new TextView(this); tv.setLayoutParams(new

我想动态地将一些视图添加到已在XML中定义的
LinearLayout

我可以将视图添加到屏幕中,但它们没有被“放在”右侧的
LinearLayout

如何从代码中获取此特定布局的引用,类似于使用
findViewById()
获取
视图

这应该可以:

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);

正如马卡斯指出的,你可以做到

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);
LinearLayout类扩展了视图类,该类本身扩展了视图类。这使得获取对布局的引用与获取对另一视图的引用一样容易

更好的版本: 在“活动/片段”中添加其他布局的步骤

LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);

快乐编码(-:

如果您的视图最终不在正确的线性布局中,这意味着您对它的引用不正确。请尝试检查您是否按id以正确的方式找到线性布局(也称为按XML文件中定义的唯一id)。没有代码,就没什么可说的了。每次我重新加载活动时,新添加的视图都不会出现。我想知道如何将这些视图添加到
视图组
,以便永久添加它们?谢谢,谢谢!只是一个说明,在我的情况下,我使用的是水平方向,但每次添加新站点时m、 它没有出现。只有当我将方向更改为垂直时,新项目才出现。答案与问题有什么关系?这就是我要找的。