Sunday, 18 August 2013

How to create widget button in corona DSK

In this tutorial, we will teach you the method of creating Widget button in your Corona SDK application.

First of all, you need to download the following 2 images and keep it with your 'main.lua'.


myButton_normal.png
 

myButton_press.png



Name the first button as: myButton_normal.png
and name the second as: myButton_press.png

Now we can start coding. Lets open main.lua. In the top of your code, require 'widget' as follows:


    local widget = require( "widget" )  


Now create a label to display the button events:
  
    local myText = display.newText( "Click on the buttons.", 0, 0,nil, 18 )
    myText.x, myText.y = display.contentCenterX, 70


Now we have to create the functions triggered by the buttons:

    local button1Press = function( event )
        myText.text = "Button 1 pressed"
    end

    local button1Release = function( event )
        myText.text = "Button 1 released"
    end

    local buttonHandler = function( event )
        myText.text = "id = " .. event.target.id .. ", phase = " .. event.phase
    end


Then just create first button as follows. This button has individual press and release functions.


    local button1 = widget.newButton{
        defaultFile = "myButton_normal.png",
        overFile = "myButton_press.png",
        onPress = button1Press,
        onRelease = button1Release,
        label = "Button 1 Label",
        emboss = true
    }

    button1.x = 160; button1.y = 160


Now we are going to create the second button. This has a single event handler function.

    
    local button2 = widget.newButton{
        defaultFile = "myButton_normal.png",
        overFile = "myButton_press.png",
        onEvent = buttonHandler,
        label = "Button 2 Label",
        id="myButton_2",
        emboss = true
    }
    button2.x = 160; button2.y = 240


 Now, save and run your application. You can see the event label and two buttons. Perform Touch, Drag and Release on the buttons and check it with the label.

Note: Please update your corona SDK version to include all new widget features.




No comments:

Post a Comment