页面无滚动内容时如何展开CoordinatorLayout内的顶部栏
实现方案
你只需要监听ViewPager2的页面切换事件,每次切换Fragment时判断当前展示的页面是否可滚动,再对应控制AppBarLayout的展开状态即可,具体实现步骤如下:
步骤1:补充AppBarLayout的ID
先给你布局里的AppBarLayout添加ID,方便后续代码调用:
<com.google.android.material.appbar.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content" app:elevation="0dp">
步骤2:给ViewPager2注册页面切换监听
在你的DetailActivity中,初始化完ViewPager2后添加页面切换回调:
private lateinit var appBarLayout: AppBarLayout private lateinit var topBar: ConstraintLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) appBarLayout = findViewById(R.id.app_bar) topBar = findViewById(R.id.top_bar) detailViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) // 获取当前显示的Fragment val currentFragment = supportFragmentManager.findFragmentByTag("f$position") val isScrollable = checkFragmentCanScroll(currentFragment) updateAppBarState(isScrollable) } }) }
步骤3:实现Fragment可滚动性判断方法
根据你Fragment内的滚动容器类型(NestedScrollView/RecyclerView等)判断页面是否可滚动:
private fun checkFragmentCanScroll(fragment: Fragment?): Boolean { fragment ?: return false // 替换为你Fragment里滚动容器的统一ID val scrollContainer = fragment.view?.findViewById<View>(R.id.scroll_container) ?: return false // 判断是否支持竖向滚动 return scrollContainer.canScrollVertically(1) || scrollContainer.canScrollVertically(-1) }
步骤4:实现AppBar状态控制逻辑
private fun updateAppBarState(isPageScrollable: Boolean) { val layoutParams = topBar.layoutParams as AppBarLayout.LayoutParams if (isPageScrollable) { // 可滚动页面恢复滚动能力 layoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP } else { // 不可滚动页面强制展开AppBar并禁用滚动 appBarLayout.setExpanded(true, true) layoutParams.scrollFlags = 0 } topBar.layoutParams = layoutParams }
内容的提问来源于stack exchange,提问作者Andrain
相关产品推荐
相关产品推荐

