Android Code Snippet How to add Custom Views programmatically

Sub Name: !!!

Description: Allows you to add Custom Views programmatically (by code)

Author: @Erel


B4X:
Sub SpecialSubThatCreatesACustomViewProgrammatically (Parent As Panel, Left As Int, Top As Int, Width As Int, Height As Int)
 Parent.LoadLayout("LayoutWithOnlyTheCustomViewMakeSureThatHandleResizeEventIsUnchecked")
 Dim v As View = Parent.GetView(Parent.NumberOfViews - 1)
 v.SetLayoutAnimated(0, 1, Left, Top, Width, Height)
End Sub



BTW, if you need access to the custom view class instance then you should add a global variable with the same name as the view and it will hold a reference to the last loaded custom view:
B4X:
Sub SpecialSubThatCreatesACustomViewProgrammatically (Parent As Panel, Left As Int, Top As Int, Width As Int, Height As Int) As B4XComboBox
 Parent.LoadLayout("LayoutWithOnlyTheCustomViewMakeSureThatHandleResizeEventIsUnchecked")
 Dim v As View = Parent.GetView(Parent.NumberOfViews - 1)
 v.SetLayoutAnimated(0, 1, Left, Top, Width, Height)
 Return GlobalVariableWithTheSameNameAsTheNameOfTheViewInTheLayoutFileYouCreated
End Sub


It is recommended to remove AutoScaleAll for that layout
.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…