|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
   AutoIt (Programación) Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  Teleco - Emisora de A.M. Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


Nuevo concurso para España, Argentina, Brasil, Chile, Colombia, Ecuador, México, Perú y Portugal.

B4A en español - Juan Antonio Villalpando
(BASIC4Android)

-- Tutorial de B4A --

Volver al índice del tutorial

____________________________

34.- Arrastra y soltar View. Drag and Drop.

- Tutoriales. Arrastrar y soltar View. Drag and Drop.

- Presentación.

Mediante código podemos arrastar y soltar los distintos Views. Posiblemente en las nuevas versiones se hará de una manera más simple.

 

El Activity es la pantalla, podemos crear una subrutina llamada Acitivity_Touch, de manera que cuando movamos el cursor por la pantalla (Activity), se obtenta la posición x e y de donde de encuentre el cursor y podamos hacer operaciones de moviemiento.

Subrutina del Tocar_Activity:

Sub Activity_Touch (Action As Int, x As Float, y As Float)

.......
End Sub

De tal manera que podemos utilizar el Panel

______________________
1.- Código con un Botón.

Código con un Botón.

- En este ejemplo creamos mediante el Designer un Layout, y lo llamamos Layout.
- Insertamos un Button1 y un Label1
- Copiamos y pegamos el código.
- Al pulsar sobre cualquier parte de la pantalla con el ratón y mover el cursor, se moverá el Button1.
- Cuando pulsamos el Button1, saldrá una caja de mensaje.

Es decir, cuando tocamos la pantalla (Activity_Touch), el Button1 se situa en la posición del cursor.

- Nota importante: este código solo funciona cuando queremos mover un solo View, en nuestro caso el Button1.

Si queremos mover dos Views de forma independiente no valdrá, ya que al mover el cursor se moverían los distintos controles a la vez.

 

'Activity module
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
' Juan Antonio Villalpando
' juana1991@yahoo.com 
End Sub

Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.

Dim Button1 As Button
Dim mapMoveObject As Map
Dim xDelta,yDelta As Int
Dim xOrigin,yOrigin As Int
Dim xVal,yVal As Int
Dim Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout") ' Cargamos el Designer
End Sub

Sub Button1_Click
Msgbox("Hello world", "This is the title")
End Sub


Sub Activity_Touch (Action As Int, x As Float, y As Float)

xVal = x : yVal = y
Label1.Text = xVal & " x " & yVal

Select Action
Case Activity.ACTION_DOWN
yDelta = yVal
xDelta = xVal
yOrigin = Button1.Top
xOrigin = Button1.Left


Case Activity.ACTION_MOVE
Button1.Top = yOrigin - yDelta + yVal
Button1.Left = xOrigin - xDelta + xVal

Case Activity.ACTION_UP
'mapMoveObject.Put("top",Panel1.Top)
'mapMoveObject.Put("left",Panel1.Left)
End Select

End Sub

______________________
2.- Código con dos Paneles y dos Botones.

Código con dos Paneles y dos Botones

- En este ejemplo creamos mediante el Designer un Layout, y lo llamamos Layout.
- Insertamos dos Paneles: Panel1 y Panel2 y dentro de cada uno Button1, Button2 respectivamente y un Label1
- Los Paneles deben tener un tamaño ligeramente superior a los Botones.
- Copiamos y pegamos el código.
- Al Pulsar sobre cada Panel marcamos su código para ser movido, de tal manera que al mover el ratón pulsado por el Activity (ya fuera del Panel) se moverá ese Panel con su Botón.

 

 

'Activity module
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Button1, Button2 As Button
    Dim Panel1, Panel2 As Panel
    'Dim mapMoveObject As Map
    Dim xDelta,yDelta As Int
    Dim xOrigin,yOrigin As Int
    Dim xVal,yVal As Int
    Dim Label1 As Label
    Dim cual As String
End Sub

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout") ' Cargamos el Designer
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
Sub Activity_Touch (Action As Int, x As Float, y As Float)

xVal = x : yVal = y
Label1.text=x & "  " & y

Select Action
        Case Activity.ACTION_DOWN
        yDelta = yVal
        xDelta = xVal
        
        Select cual
        Case "Panel1"
        yOrigin = Panel1.Top
        xOrigin = Panel1.Left
        
        Case "Panel2"
        yOrigin = Panel2.Top
        xOrigin = Panel2.Left
        End Select
        
    
    Case Activity.ACTION_MOVE
    Select cual
    Case "Panel1"
    Panel1.Top = yOrigin - yDelta + yVal
    Panel1.Left = xOrigin - xDelta + xVal
    
    Case "Panel2"
    Panel2.Top = yOrigin - yDelta + yVal
    Panel2.Left = xOrigin - xDelta + xVal
    End Select
    
    
        Case Activity.ACTION_UP
        'mapMoveObject.Put("top",Panel1.Top)
        'mapMoveObject.Put("left",Panel1.Left)
End Select

End Sub

Sub Panel1_Touch (Action As Int, X As Float, Y As Float)

     cual = "Panel1"
     Activity_Touch (Action , x , y )
    
End Sub

Sub Panel2_Touch (Action As Int, X As Float, Y As Float)

     cual = "Panel2"
     Activity_Touch (Action , x , y )
    
End Sub
Sub Button1_Click
Msgbox("Panel 1 ", "Titulo")
End Sub

Sub Button2_Click
Msgbox("Panel 2 ", "Titulo")
End Sub

______________________
3.- Código con Panel y dos Botones.

El programa siguiente también es de los foros de B4A, necesita activar la librería Reflector.

Si se va a utilizar el EditText, también será necesario la librería IME, en el ejemplo mostrado, está anulada esta librería.

Si se pulsa un Botón y se deja pulsado, podemos mover todo el Panel
Si pulsamos un Botón sale un mensaje de su posición.

Es decir, según dejemos pulsado o no, el Botón reaccionará de distinta forma: arrastrando o mostrando.

Código del Basic4Android Panel con dos botones
 ' Demo program to show a draggable panel with buttons and edittext
' bluejay July,2012
' uses Reflection library and IME library

Sub Process_Globals 'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
End Sub
Sub Globals 'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
    Dim TransparentPanelOnTop As Panel
    
    Dim BottomPanel As Panel                                    ' views that will be made draggable
    Dim Button1     As Button
    Dim Button2     As Button
    Dim Label1      As Label
    Dim TxtEdit     As EditText
    
    Dim StartX      As Float                                    ' used only for panel dragging
    Dim StartY      As Float
    Dim LastX       As Float
    Dim LastY       As Float
    Dim MoveDelta   As Float
    Dim pressed     As Boolean
    
 '   Dim SoftKey        As IME                                        ' only required if using EditText
End Sub
Sub Activity_Create(FirstTime As Boolean)
    Label1.Initialize("")                                        ' define some views to interact with
    Button1.Initialize("Button1")
    Button2.Initialize("Button2")
    TxtEdit.Initialize("dummy")                                    ' make sure the EditText gets an event listener
    BottomPanel.Initialize("")
    
  '  SoftKey.Initialize("")                                ' IME library used to force showing of soft keyboard for the EditText
    
    Label1.Text  = "Waiting for click or drag..."                ' some user instructions
    Button1.Text = "I am a Button1 CLICK ME"
    Button2.Text = "I am a Button2 CLICK ME"
    TxtEdit.Hint = "type something here"
    
    Activity.AddView(BottomPanel,0,0,100%x,100%y)               ' build the User Interface
    BottomPanel.AddView(Label1,10,10,Activity.Width - 20,60)
    BottomPanel.AddView(Button1,10,100,Activity.Width - 20,60)
    BottomPanel.AddView(Button2,10,180,Activity.Width - 20,60)
    BottomPanel.AddView(TxtEdit,10,260,Activity.Width - 20,60)

    TransparentPanelOnTop.Initialize("TransparentPanelOnTop")    ' now put a transparent panel on top of everything
    Activity.AddView(TransparentPanelOnTop,0,0,100%x,100%y)     
    TransparentPanelOnTop.Color = Colors.Transparent
    TransparentPanelOnTop.BringToFront
End Sub
Sub Activity_Resume

End Sub
Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub DeltaXY(x As Float, y As Float) As Float                    ' support routine for dragging
  Return Abs(StartX - x) + Abs(StartY - y)                      ' does not need to be the actual distance moved
End Sub

Sub TransparentPanelOnTop_Touch (Action As Int, x As Float, y As Float)
  'Note: always sends the touch action to TransparentPanelOnTop
  'Note: x and y are not integers
    
    Select Action
    Case Activity.ACTION_DOWN                                               ' everything starts with this action
        SendAction(BottomPanel,x,y,"DOWN")                                  ' PRESS a view    eg highlight a button
        StartX    = x
        StartY    = y
        LastX     = x
        LastY     = y
        MoveDelta = 0
        pressed   = True
    
    Case Activity.ACTION_MOVE
        If pressed Then                                                        ' check to see if we are really moving
          MoveDelta = Max(MoveDelta, DeltaXY(x,y))    
          If MoveDelta > 1dip Then
            SendAction(BottomPanel,StartX,StartY,"UP")                         ' un-press the view since we are now moving
            pressed = False                                                    ' skip this test for subsequent moves
          End If
        End If
        BottomPanel.Left = BottomPanel.Left + Round(x) - Round(LastX)       ' DRAG the panel left or right
        BottomPanel.Top  = BottomPanel.Top  + Round(y) - Round(LastY)       ' DRAG the panel up or down
        LastX  = x                                                            ' these MUST be floating point values
        LastY  = y
        
    Case Activity.ACTION_UP
        SendAction(BottomPanel,x,y,"UP")                                     ' make sure view not left in pressed state
        pressed   = False        
        If MoveDelta <= 1dip Then SendAction(BottomPanel,x,y,"CLICK")          ' CLICK if we have not moved

    End Select
End Sub

Sub SendAction(P As Panel, x As Int, y As Int, ActionToSend As String)
' Send a Press or Unpress or Click or Focus to a child view on a given panel
' uses reflection library (and IME library for the EditText)
' Note: x,y cordinates automatically converted to integers 

    Dim i, newx, newy As Int
    
    newx = x - P.Left                                              ' translate Top panel x,y coords to Bottom panel coords 
    newy = y - P.Top                                               ' assumes the top panel does not move and positioned at 0,0
    
    For i = P.NumberOfViews - 1 To 0 Step -1      ' start with last view added to the parent panel in case there are overlapping views
        Dim v As View       
        v = P.GetView(i) 
        If (v.Left < newx) AND ((v.Left + v.Width) > newx) AND (v.top < newy) AND ((v.top + v.Height) > newy) Then     
            Dim r As Reflector          
            r.Target = v 
            
            Select ActionToSend
              Case "DOWN"
                r.runmethod2("setPressed","True","java.lang.boolean")
              Case "UP"
                r.runmethod2("setPressed","False","java.lang.boolean")
              Case "CLICK"
                If v Is EditText Then
                  r.runmethod2("setFocusableInTouchMode","True","java.lang.boolean")  ' only required on some devices
 '                 r.RunMethod("requestFocusFromTouch")                                  ' SoftKey below will also request focus
                '  SoftKey.ShowKeyboard(v)                                              ' force the SoftKeyboard to show
                Else
                  r.RunMethod("performClick")
                End If
            End Select    
            
            Exit                                                  ' exit the for loop - only apply the action to one view on the panel      
        End If   
    Next
End Sub

'These buttons and labels are on the BottomPanel underneath the TransparentPanelOnTop
Sub Button1_Click
    Label1.Text = "You Clicked Button1 with positions : X = " & StartX & " Y = " & StartY
End Sub
Sub Button2_Click
    Label1.Text = "You Clicked Button2 with positions : X = " & StartX & " Y = " & StartY
End Sub

______________________
4.- Código mediante Classes.

En este tutorial presenta la creación de Classes y lo hacen con un ejemplo de arrastrar view.

El ejemplo lo podemos realizar de la siguiente manera:

1.- Mediante el Designer creamos un Layout y lo llamamos "1", contendrá un Button1, Button2 y un EditText1.

2.- Luego copiamos en el proyecto (Main) la parte:

'Main activity module
Sub process_globals

End Sub

Sub Globals
Dim Button1 As Button
Dim Button2 As Button
Dim EditText1 As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
Dim dv1, dv2, dv3 As DraggableView
dv1.Initialize(Activity, Button1)
dv2.Initialize(Activity, Button2)
dv3.Initialize(Activity, EditText1)
End Sub

3.- Después creamos una clase:
Project / Add New Module / Class Module

y le ponemos de nombre: DraggableView

y copiamos desde...
'***************************
'DraggableView class module

...hacia abajo. Como se observa en el dibujo superior.

4.- Activamos la librería Reflection.

De esta manera podemos mover los Botones y el Edittext por la pantalla.

NOTA: los controles se pueden mover pero no funcionan sus eventos.

- Un proyecto que podríamos hacer es r un puzzle. Tendríamos varias partes de una imagen desordenadas y mediante esta clase nos daría la posibilidad de situarlas en el lugar apropiado para construir el puzzle.

El ejemplo anterior explica lo que es una clase. Es un trozo de código que realiza alguna acción, puede contener variables, algoritmos, eventos,... y podemos utilizar en cualquier otra aplicación.

________________________________

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información