Java returns "ScrollView can host only one direct child" 当只有一个直接 child

Java returns "ScrollView can host only one direct child" when there's only one direct child

我有自己的定制 ScrollView 作为我的 layout 的主要 View,其中包含一个 FrameLayout 和其他每个 View放在里面。看起来像这样(这是 sm_layout.xml):

<com.effeleven.utils.CustomScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollView"
    android:background="@color/white"
    android:clickable="true">

    <FrameLayout...>

</com.effeleven.utils.CustomScrollView>

当我使用默认 Android ScrollView 时没有抛出这个异常。现在我需要一个自定义的,因为我需要处理 ScrollView 中的滚动事件(我有一个 mapFragmentListView,我无法用任何东西替换它,因为我遵循设计模式)。是什么导致了异常,因为我的 CustomScrollView 只包含一个 FrameLayout,就像之前的 ScrollView 一样?

这是我的 CustomScrollView class:

public class CustomScrollView extends ScrollView {

public CustomScrollView(Context context) {
    super(context);
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    layoutInflater.inflate(R.layout.sm_layout, this, true);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    final int action = ev.getAction();
    switch (action)
    {
        case MotionEvent.ACTION_DOWN:
            super.onTouchEvent(ev);
            break;

        case MotionEvent.ACTION_MOVE:
            return false;

        case MotionEvent.ACTION_CANCEL:
            super.onTouchEvent(ev);
            break;

        case MotionEvent.ACTION_UP:
            return false;

    }

    return false;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    super.onTouchEvent(ev);
    return true;
}
}

在您的 CustomScrollView 中,您包含了另一个使用 LayoutInflater 的布局,这导致了您的问题。尝试评论布局,看看它是否有效。

阅读ScrollView

A view group that allows the view hierarchy placed within it to be scrolled. Scroll view may have only one direct child placed within it .

原因

layoutInflater.inflate(R.layout.sm_layout, this, true);

您包含了多个 xml 属性作为 ScrollView 的 子项。您持有 sm_layout.xml 。您 应该从 Class 中删除它。