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:
Code: Copy
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
 
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.
 
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?
 
Back
Top