Corona Button not passing focus to scrollView - button

I am having an issue with scrolling when buttons are on the scrollView. The problem is the issue of events not being handled properly. All attempts to pass focus to the scrollView have proven fruitless. An observation I have made is that in this following code, it is not printing back to me, this is even after I was scrolling correctly without the buttons in the way of it.
local function scrollListener( event )
local phase = event.phase
if ( phase == "began" ) then print( "Scroll view was touched" )
elseif ( phase == "moved" ) then print( "Scroll view was moved" )
elseif ( phase == "ended" ) then print( "Scroll view was released" )
end
-- In the event a scroll limit is reached...
if ( event.limitReached ) then
if ( event.direction == "up" ) then print( "Reached top limit" )
elseif ( event.direction == "down" ) then print( "Reached bottom limit" )
elseif ( event.direction == "left" ) then print( "Reached left limit" )
elseif ( event.direction == "right" ) then print( "Reached right limit" )
end
end
return true
end
Here is the actual code being used for the scene:
function scene:enterScene(event)
--local yell=audio.play(ahhh, {channel=1, loops=0, fadein=0})
--Creating the Background
local background=display.newImageRect("background.png", 320, 580)
background.x=160
background.y=240
--Creating the scroll view
local scrollView = widget.newScrollView
{
top = 10,
left = 10,
width = 300,
height = 500,
scrollWidth = 300,
scrollHeight = 500,
horizontalScrollDisabled = true,
listener = scrollListener
}
local button = {}
local yCount = 0
for i = 1 , 11 do
button[i] = widget.newButton{
label = "Button " .. i,
left = 0,
id = button[i],
top = yCount,
width = 300,
height = 100,
defaultFile = "menuButton.png",
onEvent = handleButtonEvent
}
yCount = yCount + 100
scrollView:insert(button[i])
end
--local background=display.newRect(160, 270, 320, 510)
--scrollView:insert( background )
local menu=display.newImageRect("menu2.png", 90, 50)
menu.x=50
menu.y=-15
function menu:touch(event)
if event.phase=="began" then
--local illBeBack=audio.play(terminator,{channel=1, loops=0, fadein=0})
display.remove(menu)
display.remove(taskBar)
display.remove(background)
taskBar = nil
background = nil
menu = nil
storyboard.gotoScene("menu")
end
return true
end
menu:addEventListener("touch", menu)
end
--Button Event Handler
local function handleButtonEvent( event )
local phase = event.phase
if ( phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
return true
end

Try passing the event.phase into scrollView like this:
scrollView:takeFocus(event.phase)

The problem was solved by removing 'local' from the 'handleButtonEvent' and 'scrollListener' functions, along with removing 'local' from the 'scrollView' widget
So it appears that in corona, or at least the program I am making, that globals must be used a lot more than what they should be, unless someone else has a solution.

Related

The buttons in my pygame menu only work on hold and not on push [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 5 days ago.
i am working through a pygame code and am in the process of creating a second menu sequentially, however unlike the first menu the second one differs in that it only works when holding down on the position of the button.
i am wondering if anyone can help differentiate what makes the two work and if there is a fix for it.
import random
import time
import pygame
pygame.init()
WIDTH = 500
HEIGHT = 500
screen = pygame.display.set_mode([WIDTH, HEIGHT])
fps = 60
timer = pygame.time.Clock()
main_menu = False
font = pygame.font.Font('freesansbold.ttf', 24)
menu_command = 0
p1score = 0
p2score = 0
class Button:
def __init__(self, txt, pos):
self.text = txt
self.pos = pos
self.button = pygame.rect.Rect((self.pos[0], self.pos[1]), (200, 40))
def draw(self):
pygame.draw.rect(screen, 'light gray', self.button, 0, 5)
pygame.draw.rect(screen, 'dark gray', self.button, 5, 5)
text = font.render(self.text, True, 'black')
screen.blit(text, (self.pos[0] + 15, self.pos[1] + 7))
def check_clicked(self):
if self.button.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
return True
else:
return False
def draw_game():
button = Button('Main Menu', (120, 450))
button.draw()
menu = button.check_clicked()
return menu
def draw_menu():
command = -1
pygame.draw.rect(screen, 'black', [100, 100, 300, 300])
#exit menu button
menu_button = Button('Exit Menu', (120, 350))
btn1 = Button('Local Match', (120, 180))
btn2 = Button('Online Match', (120, 240))
btn3 = Button('Settings', (120, 300))
menu_button.draw()
btn1.draw()
btn2.draw()
btn3.draw()
if menu_button.check_clicked():
command = 0
if btn1.check_clicked():
command = 1
if btn2.check_clicked():
command = 2
if btn3.check_clicked():
command = 3
return command
def turndecide():
time.sleep(0.1)
firstturn = -1
p1button = Button('player 1', (120, 120))
p2button = Button('player 2', (120, 180))
ranbutton = Button('Random', (120, 240))
firstturntext = font.render(f'please select who will take the first turn', True, 'black')
screen.blit(firstturntext, (20, 20))
p1button.draw()
p2button.draw()
ranbutton.draw()
if p1button.check_clicked():
firstturn = 1
if p2button.check_clicked():
firstturn = 2
if ranbutton.check_clicked():
firstturn = random.randint(1, 2)
return firstturn
def localgame():
screen.fill('white')
turn = turndecide()
if turn > 0:
screen.fill('red')
outputtext = font.render(f'player {turn} will move first', True, 'black')
screen.blit(outputtext, (20, 20))
run = True
while run:
screen.fill('white')
timer.tick(fps)
if main_menu:
menu_command = draw_menu()
if menu_command != -1:
main_menu = False
else:
main_menu = draw_game()
if menu_command > 0:
if menu_command == 1:
localgame()
if menu_command == 2:
onlinegame()
if menu_command == 3:
settings()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.flip()
pygame.quit()
i tried adding a while loop to ensure the code does not move backward as it does
def localgame():
screen.fill('white')
turn = turndecide()
testvariable = True
while testvariable:
if turn > 0:
screen.fill('red')
outputtext = font.render(f'player {turn} will move first', True, 'black')
screen.blit(outputtext, (20, 20))
but this causes the program to crash.
In your check_clicked function, it will return True only if the user is actively clicking on the button. Whether or not you show the menu is, therefore, also linked to whether or not the user is actively clicking/holding the button.
Instead, each time the button is clicked, toggle the menu option. Only toggle the menu again once the player releases the mouse and presses it again. This avoids the menu being toggled really quickly constantly while holding the button down.
Perhaps, have a can_click variable that is set to False every time a click is registered and reset to True when the mouse is released.

Object Shell.Application Open Folder In Same Explorer Window

I want to ask you a question regarding Shell.Application COM Object. The programming language I work in is AutoIT. I would like to know, how can I open a folder in the exact same Window a previous folder has been opened.
For instance, if I open the C:\Folder in a Window and it has a subfolder, then how can I make the Script open that subfolder in the same window the "parent folder" has been opened, without creating a new window for that. The only way I can open a Folder is like this:
global $ShellApplication = ObjCreate("Shell.Application")
$ShellApplication.Explore("C:\Folder")
Sleep(100)
$ShellApplication.Explore("C:\Folder\Subfolder")
but this way is the wrong way. I hope someone has got any idea about how this could be achieved.
I don't know whether this is what you want, but you can automate the current window like this:
#include <Array.au3>
Opt("SendKeyDelay", 1) ;5 milliseconds
Opt("SendKeyDownDelay", 1) ;1 millisecond
$pid = ShellExecute("explorer.exe ", #DesktopDir)
Sleep(300)
;~ $aWinList=WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
;~ _ArrayDisplay($aWinList)
ConsoleWrite($pid & #CRLF)
$handle = _WinGetHandleByPID($pid)
Sleep(2000)
SendKeepActive($handle)
Send('{F4}')
Send('^a')
Send(#AppDataCommonDir & "{ENTER}")
Func _WinGetHandleByPID($vProcess, $nShow = 1)
; Get Window Handle by PID
; Author Hubertus
; derived from Smoke_N's script with the same name,
; but to handle more than one process with the same name
; and to return handle of newest window ($nShow = 2).
;
; $vProcess = Processname(e.g. "Notepad.exe") or Processnumber(e.g. 4711 )
; $nShow = -1 "All (Visble or not)", $nShow = 0 "Not Visible Only", $nShow = 1 "Visible Only", $nShow = 2 "return handle of newest window "
; #error = 0 Returns array of matches. Array[0][0] and #extended shows number of matches.
; #error = 0 and $nShow = 2 return handle of newest window
; Array[n][0] shows windows title. Array[n][1] shows windows handle. n = 1 to #extended
; #error = 1 Process not found.
; #error = 2 Window not found.
If Not ProcessExists($vProcess) Then Return SetError(1, 0, 0) ; no matching process
Local $iWinList, $aWinList = WinList()
Local $iResult, $aResult[UBound($aWinList)][2]
Local $iProcessList, $aProcessList = ProcessList($vProcess)
If $aProcessList[0][0] = 0 Then Local $aProcessList[2][2] = [[1, 0], ["", $vProcess]]
For $iWinList = 1 To $aWinList[0][0]
For $iProcessList = 1 To $aProcessList[0][0]
If WinGetProcess($aWinList[$iWinList][1]) = $aProcessList[$iProcessList][1] Then
If $nShow > -1 And Not $nShow = (2 = BitAND(WinGetState($aWinList[$iWinList][1]), 2)) Then ContinueLoop
$iResult += 1
$aResult[$iResult][0] = $aWinList[$iWinList][0]
$aResult[$iResult][1] = $aWinList[$iWinList][1]
EndIf
Next
Next
If $iResult = 0 Then Return SetError(2, 0, 0) ; no window found
ReDim $aResult[$iResult + 1][2]
$aResult[0][0] = $iResult
If $nShow = 2 Then Return SetError(0, $iResult, $aResult[1][1])
Return SetError(0, $iResult, $aResult)
EndFunc ;==>_WinGetHandleByPID

Corona sdk composer wont got back to previous scene

I have used coronaSDK composer to have scenes in my application. i have a options button that is able to get to the options scene. however when i put a button on the option scene to go back to mainMenu scene it doesnt work
mainMenu.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- "scene:create()"
function scene:create( event )
local sceneGroup = self.view
local backgroundimg = display.newImage("image/mainBackground.png")
backgroundimg.x = display.contentWidth*0.5
backgroundimg.y = display.contentHeight*0.5
sceneGroup:insert( backgroundimg )
local function startListener( event )
composer.gotoScene( "scene.play" )
end
local start = display.newRect(65,99.5,161,161)
start.alpha = 0.01
start:addEventListener( "tap", startListener )
local function leaderListener( event )
composer.gotoScene( "scene.leaderboards" )
end
local leader = display.newRect(208,227.5,147,147)
leader.alpha = 0.01
leader:addEventListener( "tap", leaderListener )
local function optionsListener( event )
composer.gotoScene( "scene.options" )
end
local options = display.newRect(332,92.5,147,147)
options.alpha = 0.01
options:addEventListener( "tap", optionsListener )
local function quitListener( event )
os.exit()
end
local quit = display.newRect(432,240.5,120,120)
quit.alpha = 0.01
quit:addEventListener( "tap", quitListener )
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
-- "scene:hide()"
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
-- "scene:destroy()"
function scene:destroy( event )
local sceneGroup = self.view
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
options.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- "scene:create()"
function scene:create( event )
local sceneGroup = self.view
local function startListener( event )
composer.gotoScene( "scene.mainMenu" )
end
local start = display.newRect(65,99.5,161,161)
start.alpha = 1
start:addEventListener( "tap", startListener )
end
Try using:
composer.gotoScene( "mainMenu" )
Also, you are not adding the objects to the scene group. So, when the scene changes, the objects will not be removed automatically.

How to update gtable at gWidget in R?

I'm struggling to update the table data in the following code for GUI. It works to add each new request to the previous, so that it doesn't fit the screen, while I need to replace old request with the new one. Thanks! A.
require ( gWidgets )
options ( guiToolkit="RGtk2" )
window <- gwindow ( "Pilot>>" , visible = FALSE, horizontal = FALSE )
paned <- gpanedgroup ( cont = window )
group <- ggroup ( cont = paned, horizontal = FALSE )
glabel ( "FPC:" , cont = group )
entry <- gedit ( "" , cont = group )
entry [ ] <- actfpc$CURFPC ##list of codes for auto-filling
search_button <- gbutton ( "Go!" , cont = group )
addSpring ( group )
frame <- gframe ( "Supply:" , cont = paned , horizontal = FALSE,use.scrollwindow=TRUE )
addHandlerChanged ( search_button , handler = function ( h , ... ) {
##Data subset for entered value
a<-skulist[skulist$FPC==svalue(entry),]
a<-a[c("X_id","FPC","STATUS","COMMENT","DCTR","DCSTOCK")]
tbl <- gtable ( a , cont = frame, expand=TRUE )
} )
size ( frame) <- c ( 950 , 250)
visible ( window ) <- TRUE

why does the Director class make my global variables not visible to external modules in corona?

I'm doing basic stuff to understand using external classes/modules with global variables, and now I'm trying to add director. But when I added the director class, my global variables such as applyThrust then became not visible in the external class.
It worked fine before refactoring for Director. Before using director, I only had 2 files, rocket.lua and the mainScreen.lua file below was simply main.lua. I used the same globals, applyThrust and thrustForceY, and it worked.
By the way, the director functionality of switching screens appears to work fine, other than this odd side effect of making the global variables not visible.
I asked this on the corona director forums and got no response so I thought I'd try reliable STO.
Here's the files I'm using with the director stuff :
main.lua
display.setStatusBar (display.HiddenStatusBar)
local director = require ("director")
local mainGroup = display.newGroup()
local function main()
mainGroup:insert(director.directorView)
director:changeScene("menu")
return true
end
main()
menu.lua
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------------------
local playText = display.newText("Play",160, 100, "Arial", 32)
playText:setTextColor(0, 0, 255)
localGroup:insert(playText)
local function pressPlay (event)
if event.phase == "ended" then
director:changeScene ("mainScreen")
end
end
playText:addEventListener ("touch", pressPlay)
------------------------------------------------------------------------------
return localGroup
end
mainScreen.lua
local Rocket = require( "rocket" )
local physics = require( "physics" )
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------
score = 100
physics.start()
local ground = display.newRect( 60, 170, 60, 60 )
physics.addBody( ground, "static", { density=3.0, friction=0.5, bounce=0.2 } )
rocket = Rocket.new(80, 110)
local upText = display.newText("Up",160, 300, "Arial", 32)
upText:setTextColor(0, 0, 255)
------------- my global variables -----------
thrustForceY = -100
applyThrust = false
local function pressUp (event)
local t = event.target
local phase = event.phase
if( "began" == phase ) then
display.getCurrentStage():setFocus( t )
t.isFocus = true
if( not applyThrust ) then
rocket:addThrust()
end
rocket:applyForce(0, thrustForceY, rocket.x, rocket.y)
applyThrust = true
elseif "ended" == phase or "cancelled" == phase then
rocket:removeThrust()
display.getCurrentStage():setFocus( nil )
t.isFocus = false
applyThrust = false
end
return true
end
upText:addEventListener ("touch", pressUp)
----------------------------------------------
return localGroup
end
rocket.lua
module(..., package.seeall)
local physics = require( "physics" )
--constructor--------------------
function new(x, y)
rocket = display.newGroup()
local body = display.newRect( x, y, 25, 60 )
physics.addBody( body, { density=1.5, friction=0.5, bounce=0.2 } )
body.isFixedRotation = true
rocket:insert(body)
local thrust = {}
function rocket:addThrust()
thrust = display.newRect( body.x, body.y + (body.height / 2) , 10, 10 )
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
physics.addBody( thrust, { density=1.5, friction=0.5, bounce=0.2 } )
rocket:insert(thrust)
end
function rocket:removeThrust()
rocket:remove(thrust)
end
function rocket:applyForce( xForce, yForce, atPointX, atPointY )
body:applyForce( xForce, yForce, atPointX, atPointY )
end
----------------------------------------------------------------------
-- enterFrame listener for rocket
----------------------------------------------------------------------
function rocket:enterFrame (event)
if( applyThrust ) then
body:applyForce(0, thrustForceY, body.x, body.y)
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
thrust.x = body.x
else
print("applyThrust is nil")
end
end
Runtime:addEventListener("enterFrame", rocket)
return rocket
end
A global variable in Corona is as simple as using "_G." before your variable.
For example:
lives = 3
Would become:
_G.lives = 3
But Director already has functionality to pass parameters to another scene.... there is no need to use globals.
scene1.lua
local params = {
param1= "http://github.com/",
param2 = "bla-bla"
}
director:changeScene( params, "screen2", "moveFromRight" )
screen2.lua
new = function ( params )
local url = params.param1
local bla = params.param2
...
end
Good point.
Also, you can put all your variables in a file you created and access it from any module.

Resources