监听器不起作用。听众似乎是0

时间:2017-04-28 20:08:41

标签: java android listener

嘿伙计们我将此作为MainActivity:

public class LoginActivity extends AppCompatActivity {
    public interface LoginListener {
        public void onLoginSuccess();
    }

    public void onLoginSuccess() {
        //logged in and do a few other things
    }
}

这是我的第二个Activity,我想在我的MainActivity中调用onLoginSuccess()方法,你可以看到我用一个Listener来做这个......

public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {

    private LoginActivity.LoginListener mListener;

    public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
        if (mListener != null) {
            mListener.onLoginSuccess();
        }
        else{
            Toast.makeText((Activity)context, "Listener is 0", Toast.LENGTH_LONG).show();
        }
    }
}

我的问题是,每当我尝试它时,我都会回来:“我的Toast中的听众是0”......那有什么不对?

2 个答案:

答案 0 :(得分:0)

检查以下Android代码中的指纹身份验证代码

https://gist.github.com/Evin1-/6aca8421903acca0e927eaefd85bd617

答案 1 :(得分:0)

扩展我的评论:

您需要以某种方式注册mListener。执行此操作的模式是:

public class MyHandler {

    private LoginListener mListener;

    public MyHandler(LoginListener listener) {
        mListener = listener;
    }

    // ... etc...
}

LoginListener的位置:

public interface LoginListener {
    public void onLoginSuccess();
}

您的活动有:

public MyActivity implements LoginListener {

    // instantiate the handler somewhere, with a reference
    // to "this". "this" refers to the LoginListener interface
    // which is implemented.
    @Override
    public void onCreate(Bundle b) {
        mHandler = new MyHandler(this);
    }

    @Override
    public void onLoginSuccess() {
        Log.i(TAG, "Kewel beanZ");
    }
}

或者,如果您愿意,可以将LoginListener定义为活动内部的接口,并将其实例化为:

public LoginListener mListener = new LoginListener() {
    @Override
    public void onLoginSuccess() {
        Log.i(TAG, "Sweet sweet baby beanz");
    }
};

当您创建this时,请使用mListener而不是MyHandler