【问题标题】:How can I implement a generic layout with a scrolling fragment container?如何使用滚动片段容器实现通用布局?
【发布时间】:2020-04-05 01:58:24
【问题描述】:

我有一个带有单个片段的活动的通用布局:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

我的大部分活动都重用了这个布局,只是插入了不同的片段。片段由 ConstraintLayouts、LinearLayouts、RecyclerViews 等组成。如果片段有 RecyclerView,滚动效果很好。但是,如果它包含 LinearLayout 或 ConstraintLayout,则无法滚动。如果我将 FrameLayout 包装在 NestedScrollView 中,那么我可以滚动包含 LinearLayout 或 ConstraintLayout 的片段,但它会破坏具有 RecyclerView 的片段中的回收:

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.core.widget.NestedScrollView>

如何保持我的通用布局通用并让它处理它可能包含的任何类型的片段的滚动?

【问题讨论】:

    标签: android android-fragments android-recyclerview android-coordinatorlayout android-nestedscrollview


    【解决方案1】:

    有一个NestedScrollView Child的属性,

    setNestedScrollingEnabled(false)
    

    但我强烈建议不要同时使用嵌套滚动视图和回收器视图,因为它可能会导致级联问题!我建议在 RecyclerView 中使用 ItemViewTypes 来处理多种视图。只需添加一个具有 match_parent 宽度和高度的 RecyclerView。然后在您的回收器视图适配器中覆盖 getItemViewType 并使用该位置来处理要膨胀的布局。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多