我有自己定制的 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
中的滚动事件(我有一个 mapFragment
和 ListView
,我可以'替换为任何东西,因为我遵循设计模式)。是什么导致了异常,因为我的 CustomScrollView
只包含一个 FrameLayout,就像之前的 ScrollView
一样?
这是我的 CustomScrollView
类:
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;
}
}
最佳答案
阅读 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 。你应该从类中删除它。
关于当只有一个直接 child 时,Java 返回 "ScrollView can host only one direct child",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409774/