6

我为一个活动创建了一个布局文件。在这个布局中,我创建了一个带有 textview 和 edittext 的 LinearLayout。现在我想创建额外的LinearLayouts,它们看起来和包含与我原来的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);
}
4

2 回答 2

16

有几种方法可以做到这一点。
一种快速简单的方法是在循环的每次迭代中扩充一个新布局:

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)方法设置文本:

for (int i = 0; i < 10; i++) {
    ChildView child = new ChildView( this );
    child.setText("Child No. " + i);
    parent.addView(child);
}
于 2013-02-10T15:14:07.177 回答
4

您可以通过使用布局充气器来实现

通过使用这个来获得布局充气器

LayoutInflater inflater = (LayoutInflater) context.getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
LinearLayout newlayout = inflater.inflate(R.layout.yourlayout, null);

// newlayout is the copy of your layout and you can use it and to get 
// the textview and edittext do it like this

TextView text = (TextView) newlayout.findView(R.id.yourtextviewid);
text.setText("new text");
EditText et = (EditText) newlayout.findView(R.id.yourtextviewid);
于 2013-02-10T15:08:38.450 回答