简体   繁体   中英

How to call a function from a class other than MainActivity on button click in Android Java

I want to call a function on a button click in Android. All the examples so far seem to only be able to call it from MainActivity.java , but I want to call it from a different class. How would I do this?

I've tried calling it from activity_main.xml using android:on_click="myfunction()" , but this is only able to be called from MainActivity.java . I've also tried using an onClick listener, but I can't seem to get it to work.

So far I have this:

Button onoroff = (Button)findViewById(R.id.activate);
onoroff.setOnClickListener(new View.OnClickListener() {
    public void onClick()
    {
        myfunction();
    }
});

But this is showing:

; Expected

Over here onClick() *here* { .

I'm not sure if this is the correct way to do it, or if there is another way, or if I did not format this correctly. All I want to do is when the button is pressed, it will call myfunction() . Any help is greatly appreciated. Thanks!

try this :

onoroff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               myfunction();
            }
        });

Your onClick function isn't overriding properly...incorrect method signature and no @Override annotation (look at Hussein Bilal's answer). Good way to avoid this is using the auto-complete Android Studio provides.

The following is the simplified lambda form of the setOnClickListener and it should work if you replace what you have with the following:

b.setOnClickListener((View v) -> {
    myfunction();
});

You should add the @Override annotation above the onClick function. Well you cannot access static function in a non static method. And if u want to access that function in another class so make that function static and access it with the name of the class in which the function is written. And non static functions can only be called by the instance of that class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM