android: how to add children from an xml layout into a custom view

不羁岁月 提交于 2019-12-05 01:55:56
Jin35

Why don't you just add all the children to the LinearLayout from your ScrollLayout? This should be done in the onFinishInflate() method.

for (int i = 0; i<getChildCount(); i++)
{
    View v = getChildAt(i);
    removeViewAt(i);
    llContainer.addView(v);
}

When you write your structure in the XML file - all inner views are children of your custom layout. Just replace it to LinearLayout.

Jin35's answer has a serious problem: getChildCount() changes value over the iterations because we are removing the children.

This should be a better solution:

while (getChildCount() > 0) {
    View v = getChildAt(0);
    removeViewAt(0);
    llContainer.addView(v);
}

I agree Jin35's answer is flawed. Also, the svContainer is added, so we cannot continue until getChildCount() == 0.

By the end of init(), getChildCount() == 1, since svContainer has been added but the TextViews have not. By the end of onFinishInflate(), the TextViews have been added and should be at positions 1, 2, 3, 4 and 5. But if you then remove the View at position 1, the indices of the others will all decrease by 1 (standard List behaviour).

I would suggest:

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    View v;
    while ((v = getChildAt(1)) != null) {
        removeView(v);
        llContainer.addView(v);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!