如何在运行时多次添加相同的布局

时间:2017-05-20 16:08:27

标签: android

请帮助我正在设计电子邮件,例如基于app.based的电子邮件数量,布局编号也会在运行时更改,请帮帮我。

for (int i=10;i<14;i++) {
LinearLayout lay = (LinearLayout) findViewById(R.id.veticaltoinsert);
View child = getLayoutInflater().inflate(R.layout.issuelayout, null);
child.setId(i);
lay.addView(child);
}

1 个答案:

答案 0 :(得分:0)

子视图的ID不能这样设置。 以下代码未经过测试。

// this part copied from somewhere in sf, I don't remember exactly
// random a new integer
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
// create a view id
public static int generateViewId() {
    for (;;) {
        final int result = sNextGeneratedId.get();
        //
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1;
        if (sNextGeneratedId.compareAndSet(result, newValue)) {
            return result;
        }
    }
}
// In this party, just use above method and optimise a bit.
private void something() {
    //....
    LinearLayout lay = (LinearLayout) findViewById(R.id.veticaltoinsert);
    for (int i=10;i<14;i++) {
        View child = getLayoutInflater().inflate(R.layout.issuelayout, null);
        child.setId(generateViewId());
        lay.addView(child);
    }
    //
}