gouser-interfacefyne

Go lang fyne widget.list button action


Hey im trying to solve this puzzle how do i set func for every seperate button i have ? so it dosent do the same for alle 3 buttons i have

it should be possibe by using onselected i just cant figure how to get it right. and yes i did read the docs from Fyne ;=)

i know its not actual buttons, but they should have the same options as a button just by using the onselected

fyne doc regarding widget.list https://developer.fyne.io/api/v2.0/widget/list.html


package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/theme"
    "fyne.io/fyne/v2/widget"


func main() {


    a := app.New()
    a.Settings().SetTheme(theme.DarkTheme())
    W := a.NewWindow("Application-OutSight")
    W.Resize(fyne.NewSize(640, 460))

    menuBar := []strings{"Home","App-Status", "Exit"}
    
    listView := widget.NewList(func() int {
        return len(menuBar)
    }, func() fyne.CanvasObject {
        return widget.NewLabel("template")
    }, func(id widget.ListItemID, o fyne.CanvasObject) {
        o.(*widget.Label).SetText = (menuBar[id])

    })

    contenttext := widget.NewLabel("Welcome to this App")
    
    //what i want is this, but dont know how to get right
    listView.OnSelected[0] = func(id widget.ListItemID) { //button 0
            }
    listView.OnSelected[1] = func(id widget.ListItemID) { //button 1
            }
    listView.OnSelected[2] = func(id widget.ListItemID) { //buttton2
            }
            

    split := (container.NewHSplit(
        listView,
        container.NewMax(contenttext),
    ))
    split.Offset = 0.2
    W.SetContent(split)
    W.ShowAndRun()

}


Solution

  • widget.List.OnSelected has argument widget.ListItemID which is an int.

    You can use this id to called function for different items

    listView.OnSelected = func(id widget.ListItemID) {
      switch id {
        case 0:
          //call button/list-item 0 func here
        case 1:
          //call button/list-item 1 func here
        case 2:
          //call button/list-item 2 func here
        default:
    
      }
    }