Android Question [solved] finding the activity of a view, from a code module

Dave O

Well-Known Member
Licensed User
Longtime User
How do I find the activity of a given view, if I'm in a code module?

I'm passing a view to a sub in a code module, and I also need the view's activity. If I'm in an activity module, I have the "Activity" object handy, but not in a code module.

I could pass the activity as a sub parameter, but I'm already passing the view, and I'm hoping I can just find the view's activity without having to pass it explicitly.

The following code works for normal layouts, but seemingly not for those with a scrollview:
B4X:
'return the activity that the view lives in
Sub getActivityFromView(viewArg As View) As Activity
   If viewArg.Parent Is Activity Then
     Return viewArg.parent
   Else
     Return getActivityFromView(viewArg.Parent)
   End If
End Sub

I suspect that the test for "is Activity" is stumbling when it hits the scrollview in the layout hierarchy.

Any help much appreciated. Thanks!
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

Dave O

Well-Known Member
Licensed User
Longtime User
I'm writing code to show a hint for a view when you long-click it (the standard Android behaviour).

The sub (in a code module, so that any of the app's activities can use it) needs the view and the text of the hint, at a minimum. I need the activity so I can invoke a custom toast through a JavaObject (which allows me to position the toast near the view). I'll post the code very soon.
 
Upvote 0

Dave O

Well-Known Member
Licensed User
Longtime User
Reflector.GetActivity will return the current activity (android.app.Activity). This will work from a code module.
Ah, I should have seen that method in the Reflector library.

Just tried it, like this:
B4X:
Dim r As Reflector
Dim tempActivity As Activity = r.GetActivity

...which yields a Java compilation error:
B4X:
Compiling generated Java code.  Error
B4A line: 176
Dim tempActivity As Activity = r.GetActivity
javac 1.8.0_73
src\name\obrien\dave\icelock\c.java:396: error: incompatible types: Activity cannot be converted to BALayout
_tempactivity.setObject((anywheresoftware.b4a.BALayout)(_r.GetActivity((_ba.processBA == null ? _ba : _ba.processBA))));
  ^

Do I need to do a type-cast of some kind?
 
Upvote 0

Dave O

Well-Known Member
Licensed User
Longtime User
Yesireebob, that did the trick. I'll post it in the Code Snippet section.

Thanks!
 
Upvote 0
Top