Android Tutorial [B4X] I need 100 <custom view here>s. How to add programmatically?

Custom views are designed to be added with the designer.

It is however very simple to create a layout file with the custom view and load it multiple times.

B4A_NrYo4sDqsp.png

Tip: remove the call to AutoScaleAll from the designer script.

Complete example:
B4X:
Sub Globals
    Private B4XSwitch1 As B4XSwitch
End Sub

Sub Activity_Create(FirstTime As Boolean)
    For i = 1 To 20
        AddSwitch(50dip, 40dip * i, i)
    Next
End Sub

Sub AddSwitch (Left As Int, Top As Int, Tag As Object) As B4XSwitch
    Activity.LoadLayout("B4XSwitch")
    B4XSwitch1.mBase.Left = Left 'B4XSwitch1 global variable will point to the last one added
    B4XSwitch1.mBase.Top = Top
    B4XSwitch1.Tag = Tag
    Return B4XSwitch1
End Sub


Sub B4XSwitch1_ValueChanged (Value As Boolean)
    Dim switch As B4XSwitch = Sender
    Log(switch.Tag)
End Sub


1590066027706.png
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
his implies (or clarifies) that loading N layouts into an Activity (or Panel) does NOT remove the Views already present.
True. Loading a layout will never affect any other views previously loaded.

[Note: the routine does not need to be a function and return a B4XSwitch].
In a real application you will probably want to add the dynamic views to a Map or List to be able to later access them more easily.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Q: But how can I toggle all those switches when the user clicks on the activity?
A: Explanation here: [B4X] How to get <custom view here> from <CLV or any other container>
B4X:
Sub Activity_Click
    For Each v As B4XView In Activity.GetAllViewsRecursive
        If v.Tag Is B4XSwitch Then
            Dim s As B4XSwitch = v.Tag
            s.Value = Not(s.Value)
        End If
    Next
End Sub
 

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
Since you're disabling auto-scale, for a single custom view/view Is there an advantage to this method versus just instantiating a new instance of the class and using the view's .AddToParent method?
 
Top