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
- 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.
- 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.
- 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.
Related Articles
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 MoreSoftware 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 MoreBusiness, 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 MoreSoftware Development
Unlocking the Secrets of AWS Pricing: A Comprehensive Guide
Master AWS pricing with this comprehensive guide! Learn about various pricing models, key cost factors, and practical tips for optimizing your cloud spending. Unlock significant savings and efficiently manage your AWS infrastructure.
Read MoreSoftware Development
Exploring the GNU Verbatim Copying License
Dive into the GNU Verbatim Copying License (GVCL): Understand its strengths, weaknesses, and impact on open-source collaboration. Explore its unique approach to code integrity and its relevance in today's software development landscape. Learn more!
Read MoreSoftware Development
Unveiling the FSF Unlimited License: A Fairer Future for Open Source?
Explore the FSF Unlimited License: a groundbreaking open-source license designed to balance free software distribution with fair developer compensation. Learn about its origins, strengths, limitations, and real-world impact. Discover how it addresses the challenges of open-source sustainability and innovation.
Read MoreSoftware Development
Conquer JavaScript in 2025: A Comprehensive Learning Roadmap
Master JavaScript in 2025! This comprehensive roadmap guides you through fundamental concepts, modern frameworks like React, and essential tools. Level up your skills and build amazing web applications – start learning today!
Read MoreBusiness, Software Development
Building a Successful Online Gambling Website: A Comprehensive Guide
Learn how to build a successful online gambling website. This comprehensive guide covers key considerations, technical steps, essential tools, and best practices for creating a secure and engaging platform. Start building your online gambling empire today!
Read MoreAI, Software Development
Generate Images with Google's Gemini API: A Node.js Application
Learn how to build an AI-powered image generator using Google's Gemini API and Node.js. This comprehensive guide covers setup, API integration, and best practices for creating a robust image generation service. Start building today!
Read MoreSoftware Development
Discover Ocak.co: Your Premier Online Forum
Explore Ocak.co, a vibrant online forum connecting people through shared interests. Engage in discussions, share ideas, and find answers. Join the conversation today!
Read MoreSoftware Development
Mastering URL Functions in Presto/Athena
Unlock the power of Presto/Athena's URL functions! Learn how to extract hostnames, parameters, paths, and more from URLs for efficient data analysis. Master these essential functions for web data processing today!
Read MoreSoftware Development
Introducing URL Opener: Open Multiple URLs Simultaneously
Tired of opening multiple URLs one by one? URL Opener lets you open dozens of links simultaneously with one click. Boost your productivity for SEO, web development, research, and more! Try it now!
Read More
Software Development, Business
Unlocking the Power of AWS: A Deep Dive into Amazon Web Services
Dive deep into Amazon Web Services (AWS)! This comprehensive guide explores key features, benefits, and use cases, empowering businesses of all sizes to leverage cloud computing effectively. Learn about scalability, cost-effectiveness, and global infrastructure. Start your AWS journey today!
Read MoreSoftware Development
Understanding DNS in Kubernetes with CoreDNS
Master CoreDNS in Kubernetes: This guide unravels the complexities of CoreDNS, Kubernetes's default DNS server, covering configuration, troubleshooting, and optimization for seamless cluster performance. Learn best practices and avoid common pitfalls!
Read MoreSoftware Development
EUPL 1.1: A Comprehensive Guide to Fair Open Source Licensing
Dive into the EUPL 1.1 open-source license: understand its strengths, challenges, and real-world applications for fair code. Learn how it balances freedom and developer protection. Explore now!
Read MoreSoftware Development
Erlang Public License 1.1: Open Source Protection Deep Dive
Dive deep into the Erlang Public License 1.1 (EPL 1.1), a crucial open-source license balancing collaboration and contributor protection. Learn about its strengths, challenges, and implications for developers and legal teams.
Read MoreSoftware Development
Unlocking Kerala's IT Job Market: Your Path to Data Science Success
Launch your data science career in Kerala's booming IT sector! Learn the in-demand skills to land high-paying jobs. Discover top data science courses & career paths. Enroll today!
Read More
Software Development
Automation in Software Testing: A Productivity Booster
Supercharge your software testing with automation! Learn how to boost productivity, efficiency, and accuracy using automation tools and best practices. Discover real-world examples and get started today!
Read MoreSoftware Development
Mastering Anagram Grouping in JavaScript
Master efficient anagram grouping in JavaScript! Learn two proven methods: sorting and character counting. Optimize your code for speed and explore key JavaScript concepts like charCodeAt(). Improve your algorithms today!
Read More
Software Development
Mastering Kubernetes Deployments: Rolling Updates and Scaling
Master Kubernetes Deployments for seamless updates & scaling. Learn rolling updates, autoscaling, and best practices for high availability and efficient resource use. Improve your application management today!
Read More