-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
togglebuttongroup.go
71 lines (61 loc) · 1.7 KB
/
togglebuttongroup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package widgets
import (
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/widget"
)
// Lays out multiple buttons horizontally with no padding,
// and uses button.Importance to highlight exactly one which is "active".
// Similar to a segmented control in other UI toolkits.
type ToggleButtonGroup struct {
widget.BaseWidget
buttonContainer *fyne.Container
activeBtnIdx int
}
func NewToggleButtonGroup(activatedBtnIdx int, buttons ...*widget.Button) *ToggleButtonGroup {
t := &ToggleButtonGroup{}
t.ExtendBaseWidget(t)
t.buttonContainer = container.New(layout.NewCustomPaddedHBoxLayout(0))
for i, b := range buttons {
b.Importance = widget.MediumImportance
t.buttonContainer.Add(b)
prevOnTapped := b.OnTapped
b.OnTapped = func(i int) func() {
return func() {
if t.onTapped(i) && prevOnTapped != nil {
prevOnTapped()
}
}
}(i)
}
if activatedBtnIdx >= 0 && activatedBtnIdx <= len(buttons) {
buttons[activatedBtnIdx].Importance = widget.HighImportance
}
return t
}
func (t *ToggleButtonGroup) ActivatedButtonIndex() int {
return t.activeBtnIdx
}
func (t *ToggleButtonGroup) SetActivatedButton(idx int) {
changed := t.activeBtnIdx != idx
t.activeBtnIdx = idx
for i, b := range t.buttonContainer.Objects {
if i == idx {
b.(*widget.Button).Importance = widget.HighImportance
} else {
b.(*widget.Button).Importance = widget.MediumImportance
}
}
if changed {
t.Refresh()
}
}
func (t *ToggleButtonGroup) onTapped(btnIdx int) bool {
changed := t.activeBtnIdx != btnIdx
t.SetActivatedButton(btnIdx)
return changed
}
func (t *ToggleButtonGroup) CreateRenderer() fyne.WidgetRenderer {
return widget.NewSimpleRenderer(t.buttonContainer)
}