beeware / briefcase-android-gradle-template

A template for generating Android Gradle projects with Briefcase
MIT License
18 stars 19 forks source link

Add CustomView & IView #27

Closed paulproteus closed 3 years ago

paulproteus commented 3 years ago

Summary

Implement fake-subclassing for the android.graphics.View class: Add CustomView class, which delegates onDraw() to IView interface, which can be implemented in Python.

Action

Russell, if you're willing to review this and give me naming advice, and/or merge it into dev & 3.7 & 3.8 & 3.9, that would help as I build the toga_android Canvas widget.

PR Checklist:

Screenshot

Here is a picture of Python drawing a black circle on the canvas using this approach.

image

Here is a full example app that uses it.

Here is a snippet to give you the idea.

class PlatformIndependentCanvasWidget:
    @property
    def _impl(self):
        impl = getattr(self, '__impl', None)
        if impl is None:
            self.__impl = CanvasWidget()
        return self.__impl

class CanvasWidget:
    def __init__(self):
        super().__init__()
        self.custom_view = CustomView(toga_android.widgets.base._get_activity().getApplicationContext())
        self.custom_view.setView(MicroCustomCanvasView())

    @property
    def native(self):
        return self.custom_view

class MicroCustomCanvasView(IView):
    def onDraw(self, canvas):
        paint = Paint()
        paint.setColor(Color.BLACK)
        paint.setAntiAlias(True)
        paint.setStrokeWidth(5.0)
        canvas.drawOval(0.0, 0.0, 400.0, 400.0, paint)