简体   繁体   中英

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

I have my own custom made ScrollView as a main View of my layout , which contains one single FrameLayout and every other View is put inside it. It looks like this (this is 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>

I did not have this exception thrown when I used the default Android ScrollView . Now I need a custom one, because I need to handle the scroll events inside the ScrollView (I have a mapFragment and ListView , which I can't replace with anything, because I follow a design pattern). What can be causing the exception, since my CustomScrollView contains only one FrameLayout, just like the previous ScrollView did?

This is my 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;
}
}

In your CustomScrollView you are including another layout using LayoutInflater which is causing you the problem. Try commenting the layout and see if it works.

Read 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 .

Cause

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

You have included more than one xml Attributes as children of a ScrollView . You are holding sm_layout.xml . You should remove this from Class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM