11

在我的 xml 布局中,我有一个自定义视图,我将在其中放置一些孩子,例如:

<com.proj.layouts.components.ScrollLayout
    android:id="@+id/slBody"
    android:layout_width="700dp"
    android:layout_height="400dp">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="child1"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="child2"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="child3"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="child4"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="child5"/>
</com.proj.layouts.components.ScrollLayout>

让我再解释一下。我编写了一个自定义 ScrollView,其中我已经为孩子定义了一个容器。所以我只想把它们放在那里。

public class ScrollLayout extends LinearLayout {
    // View responsible for the scrolling
    private FrameLayout svContainer;
    // View holding all of the children
    private LinearLayout llContainer;

    public ScrollLayout(Context context) {
        super(context);
        init();
    }

    public ScrollLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        super.removeAllViews(); // kill old containers


        svContainer = new HorizontalScroll(getContext());
        llContainer = new LinearLayout(getContext());
        llContainer.setOrientation(orientation);
        svContainer.addView(llContainer);

        svContainer.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        llContainer.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        addView(svContainer);


    }

    ... I left out the part which takes care of the scroll event ...
}

将 Child* 添加到 llContainer 的方法是什么?

4

3 回答 3

11

你为什么不把所有的孩子都添加到LinearLayoutfrom your中ScrollLayout?这应该在onFinishInflate()方法中完成。

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

当您在 XML 文件中编写结构时 - 所有内部视图都是自定义布局的子级。只需将其替换为LinearLayout.

于 2012-02-13T11:22:17.943 回答
8

Jin35 的回答有一个严重的问题:getChildCount()在迭代中改变值,因为我们正在移除孩子。

这应该是一个更好的解决方案:

while (getChildCount() > 0) {
    View v = getChildAt(0);
    removeViewAt(0);
    llContainer.addView(v);
}
于 2013-12-10T11:07:13.417 回答
5

我同意 Jin35 的回答是有缺陷的。此外,添加了 svContainer,因此在 getChildCount() == 0 之前我们无法继续。

在 init() 结束时,getChildCount() == 1,因为 svContainer 已添加但 TextViews 尚未添加。在 onFinishInflate() 结束时,TextViews 已经被添加并且应该在位置 1、2、3、4 和 5。但是如果你然后删除位置 1 的 View,其他的索引将全部减少 1(标准列表行为)。

我会建议:

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

    View v;
    while ((v = getChildAt(1)) != null) {
        removeView(v);
        llContainer.addView(v);
    }
}
于 2015-09-27T09:59:00.470 回答