Read the original article:How to Create Self-Centering Horizontal Navigation with List Component
How to Create Self-Centering Horizontal Navigation with List Component
Requirement Description
Implement a horizontal scrolling navigation bar with the following features:
- Support horizontal scrolling navigation with click-to-switch functionality
- Automatically scroll to the target position when clicked
- Display the target item centered within the container
- Dynamically highlight the currently selected item
Background Knowledge
- List is a core component for displaying dynamic data collections, supporting scrolling and dynamic updates. You can use listDirection to set the List component's arrangement direction.
- Scroll is a scrollable container component. When the layout size of child components exceeds the parent component's size, the content can scroll.
- scrollToIndex: Scrolls to a specified index with support for setting additional scroll offset.
Implementation Steps
- Define a CityList component containing a Scroller and a focusIndex state
- When calling the scrollToIndex() method, pass ScrollAlign.CENTER as the third parameter to specify the scroll alignment method
- Each tab item updates the focusIndex and scrolls to the corresponding position when clicked
- Control the background color of the currently selected tab based on focusIndex
Code Snippet / Configuration
@Entry
@Component
struct CityList {
private listScroller: Scroller = new Scroller();
@State focusIndex: number = 0
@State allListString: string[] = ['111', '222', '333', '444', '555', '666', '777', '888', '999']
@Builder
child(tabName: string, tabIndex: number) {
Column() {
Text(tabName)
.fontSize(18)
.padding(4)
}
.borderRadius(3)
.onClick(() => {
this.focusIndex = tabIndex
this.listScroller.scrollToIndex(tabIndex, true, ScrollAlign.CENTER)
})
.margin({ left: tabIndex === 0 ? 20 : 4, right: tabIndex === this.allListString.length - 1 ? 20 : 4 })
.backgroundColor(tabIndex === this.focusIndex ? '#0088FF' : '#F8F9F7')
}
build() {
List({ scroller: this.listScroller }) {
ForEach(this.allListString, (item: string, index: number) => {
ListItem() {
this.child(item, index)
}
}, (item: string) => item)
}
.scrollBar(BarState.Off)
.listDirection(Axis.Horizontal)
.backgroundColor('#FFF1F3')
.alignListItem(ListItemAlign.Center)
.height(60)
.margin({ top: 100 })
}
}
Test Results
The implementation successfully demonstrates:
- Horizontal scrolling navigation with smooth animations
- Click-to-center behavior for selected items
- Dynamic highlighting with background color changes
- Proper margin handling for first and last items
Limitations or Considerations
- This example supports API Version 19 Release and above
- Compatible with HarmonyOS 5.1.1 Release SDK and above
- Requires DevEco Studio 5.1.1 Release or later for compilation

Top comments (0)