|
6 | 6 | from toga.constants import CENTER, JUSTIFY, LEFT, RIGHT
|
7 | 7 |
|
8 | 8 |
|
| 9 | +def _get_activity(_cache=[]): |
| 10 | + """ |
| 11 | + Android Toga widgets need a reference to the current activity to pass it as `context` when creating |
| 12 | + Android native widgets. This may be useful at any time, so we retain a global JNI ref. |
| 13 | +
|
| 14 | + :param _cache: List that is either empty or contains 1 item, the cached global JNI ref |
| 15 | + """ |
| 16 | + if _cache: |
| 17 | + return _cache[0] |
| 18 | + # See MainActivity.onCreate() for initialization of .singletonThis: |
| 19 | + # https://github.com/beeware/briefcase-android-gradle-template/blob/3.7/%7B%7B%20cookiecutter.formal_name%20%7D%7D/app/src/main/java/org/beeware/android/MainActivity.java |
| 20 | + if MainActivity.singletonThis is None: |
| 21 | + raise ValueError("Unable to find MainActivity.singletonThis from Python. This is typically set by " |
| 22 | + "org.beeware.android.MainActivity.onCreate().") |
| 23 | + _cache.append(MainActivity(__jni__=java.NewGlobalRef(MainActivity.singletonThis))) |
| 24 | + return _cache[0] |
| 25 | + |
| 26 | + |
9 | 27 | class Widget:
|
10 | 28 | def __init__(self, interface):
|
11 | 29 | self.interface = interface
|
12 | 30 | self.interface._impl = self
|
13 | 31 | self._container = None
|
14 | 32 | self.native = None
|
15 |
| - # In Android, there is only one `app` (i.e., `Activity)`. Android widgets need a reference to |
16 |
| - # the current activity to pass it as `context` when creating native Android widgets. |
17 |
| - # |
18 |
| - # This may happen at any time, so we need a global JNI ref. |
19 |
| - self._native_activity = MainActivity(__jni__=java.NewGlobalRef(MainActivity.singletonThis)) |
| 33 | + self._native_activity = _get_activity() |
20 | 34 | self.create()
|
21 | 35 | # Immediately re-apply styles. Some widgets may defer style application until
|
22 | 36 | # they have been added to a container.
|
|
0 commit comments