How to reference the current or main activity from another class

后端 未结 13 985
难免孤独
难免孤独 2021-01-30 12:39

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But ofte

13条回答
  •  情深已故
    2021-01-30 13:04

    We built a framework for this. We have a BaseActivity class that inherits from Activity and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity that returns the activity on top of our privately-managed stack.

    It is kinda hacky, but it works. I'm not sure I would recommend it though.

提交回复
热议问题