Search code examples
androidpythonchaquopy

How to call my function directly in Chaquopy?


How to call a function I wrote using Chaquopy?

I used sample from documentation and it worked well. I could put the text on a label using Python. Then I created a button and want to call my function (for example, my_func):

from demo.chaquopy.pythonactivity import R

from java import static_proxy, Override, jvoid

from android.os import Bundle

from android.support.v7.app import AppCompatActivity


class MainActivity(static_proxy(AppCompatActivity)):

    @Override(jvoid, [Bundle])
    def onCreate(self, state):
        AppCompatActivity.onCreate(self, state)
        self.setContentView(R.layout.activity_main)
        self.findViewById(R.id.label).setText("Hello From Python!")

    def my_func(self):
        self.findViewById(R.id.label).setText("Another text")

I tried to write 'android:onclick' as with Java functions, and it doesn't work. And I couldn't find it in samples and documentation. Please can anyone help? Thanks a lot in advance.


Solution

  • To declare a listener in XML, the method has to be visible from Java. You can make it visible like this:

    from java import method
    from android.view import View
    
    class MainActivity(...):
    
        @method(jvoid, [View])
        def my_func(self):
            ...