Published 2 months ago

HarmonyOS Next: Building a Cross-Device News Application

Software Development
HarmonyOS Next: Building a Cross-Device News Application

HarmonyOS Next: Building a Cross-Device News Application

This article delves into the intricacies of developing a news and information application for Huawei's HarmonyOS Next, focusing on cross-device adaptability and consistent user experience. We'll explore key architectural designs and best practices, demonstrating how to create a truly unified experience across mobile phones, tablets, and PCs. This guide is intended for developers of all levels, offering practical examples and insights into optimizing your application for HarmonyOS Next's unique capabilities.

Architectural Design for Multi-terminal Adaptation

Common UI Structures of News Applications

News applications typically employ three common UI structures: list style, card style, and grid style. The list style, ideal for displaying numerous headlines, prioritizes clear, quick browsing. The card style enhances visual appeal with richer elements like images and summaries. Lastly, the grid style maximizes screen space, effectively showcasing many news items with small thumbnails, particularly useful for larger displays.

How HarmonyOS Next Responds to the Differential Layouts of Mobile Phones, Tablets, and PCs

  1. Mobile Phones: Mobile screens demand simplicity and ease of one-handed use. A single-column layout, with a card-style UI, is generally best. Employ adaptive layouts to ensure cards resize perfectly regardless of screen dimensions.
  2. Tablets: Tablets afford more screen real estate. Consider dual-column or multi-column layouts, balancing information density and usability. Responsive layouts are crucial here, dynamically switching between single- and dual-column cards based on screen size.
  3. PCs: PC screens allow for more complex layouts. A three-column structure – navigation bar (left), news list (center), article details (right) – effectively leverages available space. Utilize a grid layout system for precise control over column widths and proportions.

Using Adaptive Layout to Achieve UI Changes within a Single Screen

Adaptive layouts are essential for automatically adjusting UI elements within a single screen. For example, a news detail page should dynamically resize images and text to fit the available width. Using the Flex layout's flexGrow and flexShrink properties ensures proportional scaling regardless of screen size, preventing both cramped and excessively spaced layouts.

@Entry
@Component
struct NewsDetailPage {
    @State articleImage: Resource = $r('app.media.newsImage')
    @State articleContent: string = 'This is the detailed content of a news article...'
    build() {
        Flex({ direction: FlexDirection.Row }) {
            Image(this.articleImage).width(200).height(150).objectFit(ImageFit.Contain).flexGrow(0).flexShrink(1)
            Column() {
                Text('News Title').fontSize(20).fontWeight(500)
                Text(this.articleContent).fontSize(14).opacity(0.8)
            }
              .flexGrow(1).flexShrink(1).paddingStart(10)
        }
          .width('100%').height('100%')
    }
}

Implementing a News Reading Interface across Devices

To create a cohesive reading experience across various devices, combine adaptive and responsive layouts. Tailor news content display to match screen size and layout structure. On mobile phones, vertical, card-style layouts work well; tablets and PCs can leverage multi-column cards. Consistency in the news detail page is key, ensuring clear text formatting and optimal image rendering regardless of device.

Listening to Breakpoints to Implement the Three-column Mode (Navigation Bar + Information List + Article Details) on Large-screen Devices

On larger displays (PCs and some tablets), a three-column layout proves ideal. Leverage breakpoint listeners with GridRow and GridCol components for dynamic layout switching.

@Entry
@Component
struct BigScreenNewsLayout {
    @State currentBreakpoint: string ='sm'
    @State articleList: Array<{ title: string, content: string }> = [
        { title: 'News 1', content: 'The content of News 1' },
        { title: 'News 2', content: 'The content of News 2' }
    ]
    @State selectedArticleIndex: number = 0
    build() {
        GridRow({ breakpoints: { value: ['840vp'], reference: BreakpointsReference.WindowSize } }) {
            GridCol({ span: { sm: 12, md: 3, lg: 2 } }) {
                // Navigation Bar
                Column() {
                    ForEach(articleList, (article, index) => {
                        Text(article.title).fontSize(16).onClick(() => {
                            this.selectedArticleIndex = index
                        })
                    })
                }
            }
            GridCol({ span: { sm: 12, md: 6, lg: 4 } }) {
                // Information List
                List() {
                    ForEach(articleList, (article, index) => {
                        ListItem() {
                            Text(article.title).fontSize(16)
                        }
                    })
                }
            }
            GridCol({ span: { sm: 12, md: 12, lg: 6 } }) {
                // Article Details
                Column() {
                    Text(articleList[this.selectedArticleIndex].content).fontSize(14)
                }
            }
        }
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}

By monitoring breakpoint changes, the application seamlessly switches to a three-column mode when the screen width exceeds 840vp.

The Combination of Swiper + Grid to Adjust the Arrangement of Information Cards on Mobile Phones

On mobile devices, enhance browsing efficiency by combining Swiper (for carousel effects to highlight popular news) and Grid (for arranging other news cards). This maximizes limited screen space.

@Entry
@Component
struct MobileNewsLayout {
    @State newsData: Array<{ title: string, image: Resource }> = [
        { title: 'News 1', image: $r('app.media.news1Image') },
        { title: 'News 2', image: $r('app.media.news2Image') },
        { title: 'News 3', image: $r('app.media.news3Image') }
    ]
    build() {
        Column() {
            Swiper() {
                ForEach(newsData.slice(0, 3), (news) => {
                    GridRow() {
                        GridCol({ span: 12 }) {
                            Column() {
                                Image(news.image).width('100%').height(150).objectFit(ImageFit.Contain)
                                Text(news.title).fontSize(16).textAlign(TextAlign.Center)
                            }
                        }
                    }
                })
            }
            .autoPlay(true).indicator(true)
            GridRow() {
                ForEach(newsData.slice(3), (news) => {
                    GridCol({ span: 6 }) {
                        Column() {
                            Image(news.image).width('100%').height(100).objectFit(ImageFit.Contain)
                            Text(news.title).fontSize(14).textAlign(TextAlign.Center)
                        }
                    }
                })
            }
        }
          .width('100%').height('100%')
    }
}

Adaptation in the Free Window Mode to Ensure that the Content Does Not Shift When the Window Is Adjusted

In free window mode, maintaining content position requires a combination of adaptive and responsive layouts. Setting window size limits (minWindowWidth, maxWindowHeight) prevents layout instability from excessive resizing. Line wrapping, hiding, and breakpoint adjustments ensure content readjusts smoothly with window size changes.

@Entry
@Component
struct FreeWindowAdaptiveLayout {
    @State currentBreakpoint: string ='sm'
    build() {
        GridRow({ breakpoints: { value: ['600vp'], reference: BreakpointsReference.WindowSize } }) {
            GridCol({ span: { sm: 12, md: 6 } }) {
                Column() {
                    // News Content
                    Text('This is a news content that needs to be displayed normally under different window sizes').fontSize(14)
                }
            }
            GridCol({ span: { sm: 12, md: 6 } }) {
                // Related Picture
                Image($r('app.media.newsImage')).width('100%').aspectRatio(1).when(this.currentBreakpoint ==='sm', (image) => image.height(100)).when(this.currentBreakpoint!=='sm', (image) => image.height(150))
            }
        }
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}

Strategies for Optimizing the Experience and Dynamic Adaptation

Optimization through Media Queries: Dynamically Adjusting Fonts, Pictures, Spacing, etc. under Different Screen Sizes

Media queries allow for dynamic adjustments to font sizes, image dimensions, and spacing based on screen size. Smaller screens benefit from smaller fonts, larger spacing, and reduced image sizes, while larger screens can handle denser layouts with increased sizes and reduced spacing.

@Entry
@Component
struct MediaQueryOptimization {
    @State currentBreakpoint: string ='sm'
    build() {
        Column() {
            Text('News Title').fontSize(this.currentBreakpoint ==='sm'? 16 : 20).fontWeight(500)
            Image($r('app.media.newsImage')).width(this.currentBreakpoint ==='sm'? 100 : 200).height(this.currentBreakpoint ==='sm'? 100 : 150).objectFit(ImageFit.Contain)
            Text('News Content').fontSize(this.currentBreakpoint ==='sm'? 12 : 14).opacity(0.8).padding({ top: this.currentBreakpoint ==='sm'? 5 : 10 })
        }
          .width('100%').height('100%')
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}

Presentation Modes of the Navigation Bar on Different Ends (Hiding, Folding, Sidebar Switching)

Consider adaptive navigation bar presentation. Mobile phones may benefit from hidden or collapsible navigation bars, accessible via a dedicated button. Tablets and PCs can employ persistent sidebars for greater convenience.

@Entry
@Component
struct NavBarAdaptation {
    @State isNavBarVisible: boolean = false
    @State currentBreakpoint: string ='sm'
    build() {
        Column() {
            if (this.currentBreakpoint ==='sm') {
                Button('Expand Navigation').onClick(() => {
                    this.isNavBarVisible =!this.isNavBarVisible
                })
                if (this.isNavBarVisible) {
                    Column() {
                        // Navigation Options
                        Text('Home').fontSize(16).onClick(() => { /* Navigation logic */ })
                        Text('Categories').fontSize(16).onClick(() => { /* Navigation logic */ })
                    }
                }
            } else {
                // Sidebar Navigation on Tablets and PCs
                SideBarContainer(SideBarContainerType.Embed) {
                    Column() {
                        Text('Home').fontSize(16).onClick(() => { /* Navigation logic */ })
                        Text('Categories').fontSize(16).onClick(() => { /* Navigation logic */ })
                    }
                }
                  .sideBarWidth(200).showSideBar(true)
            }
        }
          .width('100%').height('100%')
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
                if (breakpoint!=='sm') {
                    this.isNavBarVisible = true
                }
            })
    }
}

User Interaction Optimization (Keyboard/Mouse Operations on Large-screen Ends vs. Touch Gestures on Mobile Ends)

Optimize user interaction based on device input. Large-screen devices should benefit from keyboard shortcuts and mouse hover effects. Mobile devices should focus on intuitive touch gestures. Detecting input methods allows tailoring interactions for optimal usability.

@Entry
@Component
struct InteractionOptimization {
    @State deviceType: string = 'unknown'
    @State isHover: boolean = false
    aboutToAppear() {
        // Get the device type
        this.deviceType = deviceInfo.deviceType
    }
    build() {
        Column() {
            if (this.deviceType === 'tablet' || this.deviceType === 'pc') {
                // Large-screen End
                Text('News Title').fontSize(20).onHover((isHover) => {
                    this.isHover = isHover
                }).when(this.isHover, (text) => text.color('#0A59F7'))
            } else {
                // Mobile End
                Text('News Title').fontSize(16).onClick(() => { /* News details logic */ })
            }
        }
          .width('100%').height('100%')
    }
}

By implementing these strategies, developers can create a superior user experience across all devices.

Conclusion

Creating a truly cross-device compatible news application on HarmonyOS Next requires careful consideration of adaptive and responsive layouts, breakpoint handling, and user interaction optimization. By leveraging the platform's capabilities and following the best practices outlined above, developers can deliver a consistent, high-quality experience to users across various devices.

Hashtags: #HarmonyOS # HarmonyOSNext # CrossDevice # AdaptiveLayout # ResponsiveDesign # UI # UX # NewsApp # MobileDevelopment # ApplicationDevelopment

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