DEV Community

SameX
SameX

Posted on

Typical Layout Case in HarmonyOS Next: Operation Banner (Banner)

Typical Layout Case in HarmonyOS Next: Operation Banner (Banner)

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system and summarize them based on practical development practices. It mainly serves as a medium for technical sharing and communication. There may inevitably be some errors or omissions. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.

In the application development of HarmonyOS Next, the operation banner (Banner) is a key element to attract users' attention and display important information. The Swiper component is a powerful assistant for implementing the banner carousel effect. Today, let's deeply analyze how to use the Swiper component to create operation banners that are adaptable to different devices.

Basic Usage of the Swiper Component

The Swiper component is the core component for implementing the banner carousel effect in HarmonyOS Next. It allows images or other content to be displayed in a carousel within a container, bringing users a dynamic and rich visual experience. Using the Swiper component is very simple. Here is a basic example code:

@Entry
@Component
struct BasicSwiperBanner {
    private data: Array<Resource> = [
        $r('app.media.banner1'),
        $r('app.media.banner2'),
        $r('app.media.banner3')
    ]
    build() {
        Swiper() {
            ForEach(this.data, (item: Resource) => {
                Image(item).width('100%').height(200)
            })
        }
          .autoPlay(true)
          .indicator(true)
          .itemSpace(10)
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, first, an array data containing multiple image resources is defined, and these images will be used as the carousel content of the banner. Then, inside the Swiper component, the array is iterated through the ForEach loop, and each image is added to the Swiper. The width of the image is set to 100%, and the height is set to 200. The autoPlay(true) property enables the banner to play automatically, the indicator(true) property displays the carousel indicator dots, which is convenient for users to know which image is currently being displayed, and the itemSpace(10) property sets the spacing between the images to 10. In this way, a simple banner carousel effect is achieved.

Adjusting the Display Quantity of the Swiper Component under Different Breakpoints

In order to make the banner achieve the best display effect on different devices, we need to adjust the number of images displayed in the Swiper component according to the change of the device screen size. This is where the displayCount property of the Swiper component comes into play. By combining breakpoints with the displayCount property, we can achieve displaying different numbers of images under different screen sizes. Here is an example code:

import { BreakpointSystem, BreakPointType } from '../common/breakpointsystem'

@Entry
@Component
export default struct Banner {
    private data: Array<Resource> = [
        $r('app.media.banner1'),
        $r('app.media.banner2'),
        $r('app.media.banner3'),
        $r('app.media.banner4'),
        $r('app.media.banner5'),
        $r('app.media.banner6')
    ]
    private breakpointSystem: BreakpointSystem = new BreakpointSystem()
    @StorageProp('currentBreakpoint') currentBreakpoint: string ='md'

    aboutToAppear() {
        this.breakpointSystem.register()
    }

    aboutToDisappear() {
        this.breakpointSystem.unregister()
    }

    build() {
        Swiper() {
            ForEach(this.data, (item: Resource) => {
                Image(item).width('100%').height(200)
            })
        }
          .indicator(new BreakPointType({ sm: true, md: false, lg: false }).getValue(this.currentBreakpoint)!)
          .displayCount(new BreakPointType({ sm: 1, md: 2, lg: 3 }).getValue(this.currentBreakpoint)!)
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the BreakpointSystem and BreakPointType are used to obtain the current breakpoint information. BreakPointType is used to define the property values under different breakpoints. Here, it is defined that 1 image is displayed under the sm breakpoint, 2 images are displayed under the md breakpoint, and 3 images are displayed under the lg breakpoint. The displayCount property dynamically adjusts the number of displayed images according to the current breakpoint value, and the indicator property controls the display of the indicator dots according to the breakpoint, thus achieving a personalized banner display effect on different devices.

Optimizing Banner Adaptation by Combining GridRow and Media Queries

In order to further optimize the adaptation effect of the banner on different devices, we can combine the GridRow component and media queries. The GridRow component provides grid layout capabilities, which can better control the position and size of the banner on the page; media queries can monitor various characteristic changes of the device, such as window width, portrait and landscape orientation, etc., to achieve more accurate layout adjustments. The following is an example of best practice:

import { BreakpointSystem, BreakPointType } from '../common/breakpointsystem'
import mediaQuery from '@ohos.mediaquery'

@Entry
@Component
export struct OptimizedBanner {
    private data: Array<Resource> = [
        $r('app.media.banner1'),
        $r('app.media.banner2'),
        $r('app.media.banner3')
    ]
    private breakpointSystem: BreakpointSystem = new BreakpointSystem()
    @StorageProp('currentBreakpoint') currentBreakpoint: string ='md'

    aboutToAppear() {
        this.breakpointSystem.register()
        // Media query listens to the change of window width and updates the breakpoint information
        const smListener = mediaQuery.matchMediaSync('(320vp<=width<600vp)')
        const mdListener = mediaQuery.matchMediaSync('(600vp<=width<840vp)')
        const lgListener = mediaQuery.matchMediaSync('(840vp<=width)')
        smListener.on('change', (mediaQueryResult) => {
            if (mediaQueryResult.matches) {
                this.currentBreakpoint ='sm'
            }
        })
        mdListener.on('change', (mediaQueryResult) => {
            if (mediaQueryResult.matches) {
                this.currentBreakpoint ='md'
            }
        })
        lgListener.on('change', (mediaQueryResult) => {
            if (mediaQueryResult.matches) {
                this.currentBreakpoint = 'lg'
            }
        })
    }

    aboutToDisappear() {
        this.breakpointSystem.unregister()
    }

    build() {
        GridRow() {
            GridCol({ span: { sm: 12, md: 12, lg: 12 } }) {
                Swiper() {
                    ForEach(this.data, (item: Resource) => {
                        Image(item).width('100%').height(200)
                    })
                }
                  .indicator(new BreakPointType({ sm: true, md: false, lg: false }).getValue(this.currentBreakpoint)!)
                  .displayCount(new BreakPointType({ sm: 1, md: 2, lg: 3 }).getValue(this.currentBreakpoint)!)
            }
        }
          .padding({ left: 12, right: 12, top: 16, bottom: 16 })
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, first, media queries are used to listen to the change of the window width and update the value of currentBreakpoint in real time. Then, through the GridRow and GridCol components, the Swiper component is wrapped so that it can occupy the appropriate screen space under different breakpoints. The span property of GridCol is set to occupy 12 columns under different breakpoints, ensuring that the Swiper component can be fully displayed on various screen sizes. At the same time, combined with the dynamic settings of the displayCount and indicator properties introduced before, the banner not only has a reasonable display quantity but also can adjust its position and size adaptively on different devices, bringing users a better visual experience.

By deeply understanding the basic usage of the Swiper component, adjusting the display quantity under different breakpoints, and optimizing the adaptation by combining GridRow and media queries, we can create efficient, beautiful, and adaptable operation banners for various devices in HarmonyOS Next application development. It is hoped that these contents can help developers better apply the relevant technologies in actual projects and improve the overall quality of the applications.

Top comments (0)