Corona – Simple button

The widget button works well for many circumstances. In some cases you will want to use something simpler and more customizable. Here’s is a simple script that shows the basic concepts for creating your own button with a default and active state.

Here the button is a simple rectangle. The default and active state are represented by a simple color change. This could be an image change or any other effect.

-- This function handles animating the button's 
-- default and active states. 
local function on_touch( event ) 
	local phase = event.phase	-- Get the event phase
	local button =	-- Get the event target

	-- Check the phase of the event
	if phase == "began" then 
		-- When the event begins give button focus, and color red
		display.getCurrentStage():setFocus( button )
		button:setFillColor( 255, 0, 0 )
	elseif phase == "ended" or phase == "cenceled" then 
		-- When event ends release focus, and color white
		display.getCurrentStage():setFocus( nil )
		button:setFillColor( 255, 255, 255 )

local function do_something() 
	print( "The button did something!" )

local button = display.newRect( 0, 0, 48, 48 )
button.x = display.contentCenterX
button.y = display.contentCenterY

button:addEventListener( "touch", on_touch )
button:addEventListener( "tap", do_something )

Leave a Reply

Your email address will not be published. Required fields are marked *