HarmonyOS 鸿蒙Next AppbarLayout

HarmonyOS 鸿蒙Next AppbarLayout

AppbarLayout

把AppbarLayout套在Toolbar的外面就可以解决了Toolbar被挡住的问题。

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

   <androidx.appcompat.widget.Toolbar
       android:id="@+id/toolbar"
       android:layout_width="match_parent"
       android:layout_height="?attr/actionBarSize"
       android:background="@color/colorPrimary"
       android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
       app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
       app:layout_scrollFlags="scroll|enterAlways|snap" />

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

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

但要响应RecyclerView的滚动事件还要给RecyclerView指定布局行为,然后在Toolbar中用app:layout_scrollFlags指定响应事件


更多关于HarmonyOS 鸿蒙Next AppbarLayout的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

鸿蒙Next的AppBarLayout是用于实现Material Design风格顶部应用栏的容器组件,属于ArkUI组件库。它支持与可滚动组件(如List、Grid)联动,通过scrollToIndex等接口控制滚动位置。主要特性包括:1) 响应滚动事件自动调整高度/透明度;2) 支持嵌入Title、TabBar等子组件;3) 通过AppBarState枚举(Closed/Open/HalfOpen)管理状态。使用需导入@ohos/arkui组件模块,典型布局结构为AppBarLayout嵌套TitleBar和TabBar。

更多关于HarmonyOS 鸿蒙Next AppbarLayout的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,AppBarLayout的对应实现是NavigationContainer组件。它提供了类似的工具栏交互效果,但API设计更符合HarmonyOS规范。以下是实现方案:

  1. 使用NavigationContainer作为容器:
<NavigationContainer
    ohos:width="match_parent"
    ohos:height="wrap_content">
    
    <Toolbar
        ohos:id="$+id:toolbar"
        ohos:width="match_parent"
        ohos:height="50vp"
        ohos:background_element="$color:primary"
        ohos:scroll_flags="scroll|enterAlways|snap"/>
</NavigationContainer>
  1. 关键区别点:
  • 滚动行为通过scroll_flags属性控制,与Android的layout_scrollFlags类似
  • 需要配合ListContainerScrollView使用
  • 行为字符串改为appbar_scrolling_behavior
  1. 完整示例:
<DirectionalLayout>
    <NavigationContainer
        ohos:width="match_parent"
        ohos:height="wrap_content">
        <Toolbar
            ohos:scroll_flags="scroll|enterAlways|snap"
            .../>
    </NavigationContainer>
    
    <ListContainer
        ohos:layout_behavior="appbar_scrolling_behavior"
        .../>
</DirectionalLayout>

注意HarmonyOS的组件层级和交互方式与Android Material Design有差异,建议参考官方组件文档获取最新API细节。

回到顶部