我有一个片段,其中我膨胀了"fragment_board.xml":
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.app.BoardView"
android:id="@+id/view_board"/>
</FrameLayout>如您所见,fragment_board包含一个自定义视图"BoardView",我想在其中加载以下"view_board.xml":
<com.app.BoardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:fadingEdge="none"
android:requiresFadingEdge="none"
android:overScrollMode="always"
android:id="@+id/board_scrollview_vertical">
<android.widget.HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none"
android:fadingEdge="none"
android:requiresFadingEdge="none"
android:overScrollMode="always"
android:id="@+id/board_scrollview_horizontal"
android:foregroundGravity="left">
</android.widget.HorizontalScrollView>
</com.app.BoardView>我的自定义视图包含两个滚动视图(我使用它进行平移),我希望能够在其他布局中重用它。BoardView扩展外部(垂直)滚动视图,如下所示:
public class BoardView extends ScrollView当我单独使用它时,它会膨胀得很好,我可以在充气的布局中同时滚动findViewById()视图。但是当我在布局树(例如片段)中使用它时,我会遇到问题。
在片段中,我像这样膨胀布局树:
View view = inflater.inflate(R.layout.fragment_board, container, false)从片段中,我可以findViewById()外部(垂直)滚动视图,但是对于内部(水平)滚动视图,findViewById()返回null。
在BoardView中,我会像这样膨胀:
View view = inflate(getContext(), R.layout.view_board, this);如前所述,我可以发现这两个滚动视图都很好,但当膨胀作为片段的一部分时,我得到了StackOverflowError。
原因很清楚:我先在片段中膨胀,然后在视图中再次膨胀相同的XML,这会触发视图的另一个膨胀,等等。我在这里得到一个循环引用。问题:我不知道如何将内部(水平)滚动视图添加到已经存在的布局中。我认为我需要合并或手动膨胀布局,但我不知道如何。
以下是一些参考文献(在我的例子中没有帮助):
有人能建议我该怎么做吗。如果可能的话,我希望BoardView作为一个通用组件工作,我可以在需要时插入布局树。
根据上述参考文献之一,Android并不正式支持复合组件,我的最佳选择是删除内部视图的XML布局并将它们添加到代码中吗?
发布于 2015-05-18 03:36:26
请检查这样的东西是否解决了这个问题:
fragment_board.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.app.BoardView
android:id="@+id/view_board"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>view_board.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:fadingEdge="none"
android:requiresFadingEdge="none"
android:overScrollMode="always"
android:id="@+id/board_scrollview_vertical">
<android.widget.HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none"
android:fadingEdge="none"
android:requiresFadingEdge="none"
android:overScrollMode="always"
android:id="@+id/board_scrollview_horizontal"
android:foregroundGravity="left">
</android.widget.HorizontalScrollView>
</merge>关于使用合并并包括的更多信息
https://stackoverflow.com/questions/30294267
复制相似问题