我想动态地将一些视图添加到已在XML中定义的LinearLayout
中。
我能够将视图添加到屏幕上,但它们未被放置在正确的LinearLayout
内。
如何从代码获取对该特定布局的引用,类似于使用findViewById()
获取View
的方式?
正如Marcarse所指出的,你可以这样做
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类继承了ViewGroup,而ViewGroup本身又继承自View类。这使得获取布局的引用与获取其他视图的引用一样容易。
这应该可以正常工作:
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);
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);
快乐编程(-: