Android Question add view to activity can not successful

Computersmith64

Well-Known Member
Licensed User
Longtime User
My first question is why? What are you trying to achieve? If your code does in fact work, you are instantiating an empty view, so how do you know it's not being added to the activity? Are you getting an error when you compile or run the app?

An Android view is really just a placeholder for UI components (https://developer.android.com/reference/android/view/View) - if you want to add a specific UI component, you should use one of the B4A views. Also, have a look at the documentation for the B4A View type (https://www.b4x.com/android/help/views.html#view) - which states that you cannot create new View objects, but you can assign other View types to a View variable.

If you're trying to add a B4A view to an activity, try something like this:
B4X:
Private label1 as Label

label1.initialize("label1")
label1.Text = "I am a label"
Activity.AddView(label1, 0, 0, 200dip, 40dip)

If you provide some more info about what you're actually trying to do, somebody on the forum might be able to help you.

- Colin.
 
Upvote 0

Computersmith64

Well-Known Member
Licensed User
Longtime User
B4X:
    view1.IsInitialized
Btw - .IsInitialized is read-only & generally used to determine if an object has already been initialized using .Initialize. Normal usage for it would be something like:

B4X:
Sub Globals
    Private label1 as Label
End Sub

Private Sub doStuff 
    If Not(label1.IsInitialized) Then
        label1.Initialize("label1")
        'do some other stuff
    End If
End Sub

Or

B4X:
Sub Globals
    Private label1 as Label
End Sub

Private Sub doStuff 
    Log(label1.IsInitialized)
    'do some other stuff
End Sub

- Colin.
 
Upvote 0

Computersmith64

Well-Known Member
Licensed User
Longtime User

OK - you could do that, or you can use the built in B4A click event handler for the button:
B4X:
Private b as Button

b.Initialize("btn")
Activity.AddView(b, 0, 0, 200dip, 200dip)

Private Sub btn_Click
    Log("Button was clicked.")
End Sub

- Colin.
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
Watch the video from 4:20 to 5:20, just watching 60 seconds of this video would have made your day go a lot smoothly if you were trying to catch a click event, actually any event sub. I also suggest that you quickly skim through the B4X booklets and also the B4A user guide, they were written by Klaus and will help you get to grips with using B4A, actually B4X full stop.

Auto complete events subs...
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…