Creating a Circular Button
A circular button can be created by setting the ButtonType to Circle.
Button('Circle', { type: ButtonType.Normal, stateEffect: false })
.backgroundColor(0x317aff)
.width(90)
.height(90)
Note: The borderRadius property cannot be used to override the shape of a Circle type button.
Customizing Button Appearance
Various style properties can be applied to customize button appearance.
@Entry
@Component
struct CustomButtonPage {
build() {
Column() {
Button('Rounded Button', { type: ButtonType.Normal })
.borderRadius(20)
.height(40)
Button('Styled Text', { type: ButtonType.Normal })
.fontSize(20)
.fontColor(Color.Pink)
.fontWeight(800)
Button('Colored Background').backgroundColor(0xF55A42)
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_refresh')).width(30).height(30)
}
.width(55)
.height(55)
.margin({ left: 20 })
.backgroundColor(0xF55A42)
}
}
}
Adding Click Events
Buttons can respond to user interactions by handling click events.
Button('Confirm', { type: ButtonType.Normal, stateEffect: true })
.onClick(() => {
console.log('Button clicked')
})
Practical Application Examples
Page Navigation
Buttons can trigger navigation to different application pages.
import router from '@ohos.router';
@Entry
@Component
struct NavigationExample {
build() {
List({ space: 4 }) {
ListItem() {
Button("Home").onClick(() => {
router.pushUrl({ url: 'pages/home_page' })
})
.width('100%')
}
ListItem() {
Button("Profile").onClick(() => {
router.pushUrl({ url: 'pages/profile_page' })
})
.width('100%')
}
ListItem() {
Button("Settings").onClick(() => {
router.pushUrl({ url: 'pages/settings_page' })
})
.width('100%')
}
}
.listDirection(Axis.Vertical)
.backgroundColor(0xDCDCDC).padding(20)
}
}
Form Submission
Buttons can submit user input from forms.
@Entry
@Component
struct RegistrationForm {
build() {
Column() {
TextInput({ placeholder: 'Enter username' }).margin({ top: 20 })
TextInput({ placeholder: 'Enter password' }).type(InputType.Password).margin({ top: 20 })
Button('Submit').width(300).margin({ top: 20 })
.onClick(() => {
// Handle form submission
})
}.padding(20)
}
}
Floating Action Button
A floating button can be positoined over other content.
@Entry
@Component
struct FloatingButtonExample {
private items: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
build() {
Stack() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.items, (item) => {
ListItem() {
Text('Item ' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}
}, item => item)
}.width('90%')
Button() {
Image($r('app.media.ic_public_refresh'))
.width(50)
.height(50)
}
.width(60)
.height(60)
.position({x: '80%', y: 600})
.shadow({radius: 10})
.onClick(() => {
// Handle floating button action
})
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}