简体   繁体   English

如何在Android中从函数回调到侦听器?

[英]How to call back from a function to a listener in android?

OK, I have a login class like the snippet below 好的,我有一个登录类,如下面的代码片段

public class LoginClass {

    public void login() {
        login.authorize(username,password); 
            //run activity specific code here
    }

} }

This class is quite generic, but depending on which activity calls LoginClass.login(), I would like different actions to be performed. 该类非常通用,但是根据要调用LoginClass.login()的活动,我希望执行不同的操作。

I've seen some implementation where a function is passed into the class and this function is then run on completion. 我已经看到了一些实现,其中将一个函数传递到类中,然后该函数在完成时运行。 Can anyone give me a brief example on how to do this. 谁能给我一个有关如何执行此操作的简短示例。

Functions are not first class objects in Java as seen on Android - you cannot pass a function. 在Android上,函数不是Java中的一流对象-您无法传递函数。 The ideology of Java calls for deriving from your generic class (possibly anonymously) when it needs to be specialized. Java的思想要求在需要专门化时从您的通用类派生(可能是匿名的)。 Like this: 像这样:

class MyActivity
{

    void onCreate()
    {
        MyButton.addOnClickListener(
            new LoginClass()
            {
                //Just like LoginClass, but with one method overridden
                public void login()
                {
                    super.login(); //Call the base
                    ThenSomethingElse();
                }
            });
    }
}

Alternatively, you can create hooks in the login class - functions that are called whenever custom action is needed - and override those in the activity. 另外,您可以在登录类中创建钩子(在需要自定义操作时会调用的函数),并覆盖活动中的钩子。 Such is the Java way. 这就是Java方式。

You could use Handlers to provide a callback mechanism. 您可以使用Handlers提供回调机制。

Define a handler in your caller 在呼叫者中定义处理程序

Handler mHandler = new Handler()
{
 public void handleMessage(Message msg)
 {
 }
}

Pass your handler to the login function: 将您的处理程序传递给登录功能:

LoginClass.login(mHandler);

Then send the handler a message: 然后向处理程序发送一条消息:

public void login(Handler handler)
{
 handler.sendEmptyMessage(0);
}
public class LoginClass {

    public void login(boolean b) {
        login.authorize(username,password); 
          if (b){
                 //do something
            }
          else {
                //do something
             }
    }

just use constructor argument to do this. 只需使用构造函数参数即可。

Class 1
LoginClass loginClass = new LogonClass(false)

Class 2
LoginClass loginClass = new LogonClass(true)

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

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