Published 2 months ago

Mastering Multi-Column Layouts in HarmonyOS Next

Software Development
Mastering Multi-Column Layouts in HarmonyOS Next

Mastering Multi-Column Layouts in HarmonyOS Next

This article delves into the technical intricacies of creating efficient multi-column navigation and content displays within Huawei's HarmonyOS Next. We'll explore the core logic behind single, double, and triple-column layouts, focusing on practical development techniques and optimization strategies for large-screen devices.

Core Logic: SideBarContainer and Navigation Components

HarmonyOS Next leverages the SideBarContainer and Navigation components for elegant multi-column layouts. SideBarContainer creates the sidebar housing navigation menus, while Navigation manages content display and switching. Let's examine the practical implications for various screen sizes:

  • Single-column layout (small screens): The sidebar is often hidden, revealed via user interaction.
  • Double-column layout (medium screens): Sidebar and content area are displayed simultaneously for efficient navigation and content viewing.
  • Triple-column layout (large screens): The interface is divided into side navigation, list navigation, and content areas, maximizing screen real estate.

Below is a code example illustrating the basic combination of SideBarContainer and Navigation:

// Configure in the project configuration file module.json5 {
    "routerMap": "$profile:route_map"
}
// route_map.json
{
    "routerMap": [
        {
            "name": "FileListPage",
            "pageSourceFile": "src/main/ets/pages/FileListPage.ets",
            "buildFunction": "FileListPageBuilder",
            "data": {
                "description": "File list page"
            }
        },
        {
            "name": "FileDetailPage",
            "pageSourceFile": "src/main/ets/pages/FileDetailPage.ets",
            "buildFunction": "FileDetailPageBuilder"
        }
    ]
}

// FileListPage.ets
@Builder
export function FileListPageBuilder() {
    return FileListPage();
}

@Component
export struct FileListPage {
    build() {
        Column() {
            NavDestination() {
                Text('Content of the file list page').fontSize(20).padding(20)
            }
              .title('File List')
        }
    }
}

// FileDetailPage.ets
@Builder
export function FileDetailPageBuilder() {
    return FileDetailPage();
}

@Component
export struct FileDetailPage {
    build() {
        Column() {
            NavDestination() {
                Text('Content of the file detail page').fontSize(20).padding(20)
            }
              .title('File Details')
        }
    }
}

@Entry
@Component
struct MultiColumnLayout {
    @State showSideBar: boolean = false;
    pageInfos: NavPathStack = new NavPathStack();
    @State navItems: { label: string, pagePath: string }[] = [
        {
            label: 'File List',
            pagePath: 'FileListPage'
        },
        {
            label: 'File Details',
            pagePath: 'FileDetailPage'
        }
    ];
    build() {
        SideBarContainer(SideBarContainerType.Overlay) {
            Column() {
                List() {
                    ForEach(this.navItems, (item) => {
                        ListItem() {
                            Text(item.label).fontSize(20).onClick(() => {
                                this.pageInfos.clear();
                                this.pageInfos.pushPath({ name: item.pagePath });
                            })
                        }
                    })
                }
            }
              .width('100%')
              .height('100%')
              .justifyContent(FlexAlign.SpaceEvenly)
              .backgroundColor('#F1F3F5')
            Column() {
                Navigation(this.pageInfos) {
                    List() {
                        ForEach(this.navItems, (item) => {
                            ListItem() {
                                Text(item.label).fontSize(20).onClick(() => {
                                    this.pageInfos.pushPath({ name: item.pagePath });
                                })
                            }
                        })
                    }
                }
                  .width('100%')
                  .height('100%')
                  .hideToolBar(true)
            }
        }
          .sideBarWidth(240)
          .showSideBar(this.showSideBar)
          .onChange((isOpen: boolean) => {
                this.showSideBar = isOpen;
            })
    }
}

In this example, the SideBarContainer houses the sidebar navigation menu. The Navigation component dynamically updates the displayed content based on user selections, altering the pageInfos path.

Dynamic Layout Adjustment with NavigationMode.Auto

The Navigation component's NavigationMode.Auto is crucial for dynamic layout adaptation. It automatically selects the optimal layout (Stack or Split) based on the application window's width. This eliminates the need for manual switching logic.

  • Stack mode (width < 520vp): Content is stacked, with new pages overlaying previous ones.
  • Split mode (width ≥ 520vp): The interface divides into multiple columns, displaying multiple content areas simultaneously.

For example, a news reader app might use Stack mode on a phone, showing article details after the list item is selected; it would automatically switch to Split mode on a tablet, presenting the list and details concurrently.

Optimizing Three-Column Layouts for Large Screens

Three-column navigation maximizes screen space on large devices. However, optimization is key for user experience. Adjusting column widths and enhancing interactive elements are crucial considerations. The following code exemplifies this:

// ... (previous code snippets)...

@Entry
@Component
struct OptimizedTripleColumnLayout {
    // ... (previous code snippets)...
    build() {
        SideBarContainer() {
            Column() {
                // ... (sidebar content)...
            }
              .width('100%')
              .height('100%')
              .justifyContent(FlexAlign.SpaceEvenly)
              .backgroundColor('#F1F3F5')
            Column() {
                Navigation(this.pageInfos) {
                    // ... (navigation content)...
                }
                  .mode(NavigationMode.Auto)
                  .minContentWidth(600)
                  .navBarWidth(240)
                  .backgroundColor('#FFFFFF')
                  .height('100%')
                  .width('100%')
                  .hideToolBar(true)
                  .title(this.NavigationTitle)
            }
        }
          .sideBarWidth(240)
          .minContentWidth(600)
          .showSideBar(this.showSideBar)
          .onChange((isOpen: boolean) => {
                this.showSideBar = isOpen;
            })
          .onBreakpointChange((breakpoint: string) => {
                this.curBp = breakpoint;
                if (breakpoint ==='sm') {
                    this.showSideBar = false;
                } else {
                    this.showSideBar = true;
                }
            })
    }
}

// ... (previous code snippets)...

Here, sideBarWidth and minContentWidth ensure balanced column proportions. NavigationMode.Auto handles layout adaptation, while onBreakpointChange manages sidebar visibility based on screen size. This combination delivers a flexible and efficient three-column experience.

Conclusion

Mastering multi-column layouts in HarmonyOS Next involves understanding the synergistic relationship between SideBarContainer and Navigation, along with the capabilities of NavigationMode.Auto for dynamic adaptation. By carefully tailoring these components and employing responsive design principles, developers can create robust and user-friendly applications suitable for a range of screen sizes.

Hashtags: #HarmonyOS # HarmonyOSNext # MultiColumnLayout # SideBarContainer # Navigation # UI # UX # LayoutOptimization # ResponsiveDesign # MobileDevelopment # AppDevelopment

Related Articles

thumb_nail_Unveiling the Haiku License: A Fair Code Revolution

Software Development

Unveiling the Haiku License: A Fair Code Revolution

Dive into the innovative Haiku License, a game-changer in open-source licensing that balances open access with fair compensation for developers. Learn about its features, challenges, and potential to reshape the software development landscape. Explore now!

Read More
thumb_nail_Leetcode - 1. Two Sum

Software Development

Leetcode - 1. Two Sum

Master LeetCode's Two Sum problem! Learn two efficient JavaScript solutions: the optimal hash map approach and a practical two-pointer technique. Improve your coding skills today!

Read More
thumb_nail_The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Business, Software Development

The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Digital credentials are transforming industries in 2025! Learn about blockchain's role, industry adoption trends, privacy enhancements, and the challenges and opportunities shaping this exciting field. Discover how AI and emerging technologies are revolutionizing identity verification and workforce management. Explore the future of digital credentials today!

Read More
Your Job, Your Community
logo
© All rights reserved 2024