我已经为活动创建了布局文件。在此布局中,我创建了一个带有文本视图和编辑文本的 LinearLayout。
现在我想创建额外的 LinearLayout,其外观和包含与原始 LinearLayout 完全相同的视图,但具有不同的文本。我还想在运行期间以编程方式执行此操作,因为这些 LinearLayout 的数量在运行之间会有所不同。
我读过一些关于充气机的文章,但我对它们的理解还不足以使用它们。
我在想这样的事情,显然代码是错误的,但希望你明白我想要做什么:
LinearLayout llMain = (LinearLayout)findViewById(R.id.mainLayout);
LinearLayout llToCopy = (LinearLayout)findViewById(R.id.linearLayoutToCopy);
for(int player = 0; player < size; player++)
{
LinearLayout llCopy = llToCopy.clone();
TextView tv = (TextView)llCopy.getChildAt(0);
tv.setText(players.get(player).getName());
llMain.addView(llCopy);
}
有几种方法可以实现这一点。
一种快速而简单的方法是在循环的每次迭代中膨胀一个新的布局:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);
for (int i = 0; i < 10; i++) {
View child = inflater.inflate(R.layout.child, null);
TextView tv = (TextView) child.findViewById(R.id.text);
tv.setText("Child No. " + i);
parent.addView(child);
}
setContentView(parent);
另一个(更优雅的)解决方案是创建一个扩展 LinearLayout 的单独类:
public class ChildView extends LinearLayout {
private TextView tv;
public ChildView(Context context) {
super(context);
View.inflate(context, R.layout.child, this);
tv = (TextView) findViewById(R.id.text);
}
public void setText(String text) {
tv.setText(text);
}
}
现在您可以创建一个ChildView
在循环的每次迭代中并通过设置文本setText(String text)
method:
for (int i = 0; i < 10; i++) {
ChildView child = new ChildView( this );
child.setText("Child No. " + i);
parent.addView(child);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)