简体   繁体   English

如何在Android Java中单击按钮时从MainActivity以外的类调用函数

[英]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.我想在 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.到目前为止,所有示例似乎只能从MainActivity.java调用它,但我想从不同的类调用它。 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 .我尝试使用android:on_click="myfunction()"activity_main.xml调用它,但这只能从MainActivity.java调用。 I've also tried using an onClick listener, but I can't seem to get it to work.我也试过使用onClick监听器,但我似乎无法让它工作。

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* { .在这里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() .我想要做的就是按下按钮时,它会调用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).您的 onClick 函数没有正确覆盖……不正确的方法签名和没有 @Override 注释(看看 Hussein Bilal 的回答)。 Good way to avoid this is using the auto-complete Android Studio provides.避免这种情况的好方法是使用 Android Studio 提供的自动完成功能。

The following is the simplified lambda form of the setOnClickListener and it should work if you replace what you have with the following:以下是setOnClickListener的简化 lambda 形式,如果您将现有内容替换为以下内容,它应该可以工作:

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

You should add the @Override annotation above the onClick function.您应该在 onClick 函数上方添加 @Override 注释。 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.并且非静态函数只能由该类的实例调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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