活动到活动回调侦听器 [英] activity to activity callback listener
问题描述
我们假设有2个活动Activity1
和Activity2
.我需要从methodAct2
(在Activity2
内部)调用方法methodAct1()
(在Activity1
内部).我认为应该使用回调侦听器工作-我不想使用EventBus
库!
Let's suppose 2 activities Activity1
and Activity2
. I need to call method methodAct1()
(inside Activity1
) from methodAct2
(inside Activity2
). I think it should work using callback listener - I don't want to use EventBus
libs!
我使用以下代码得到java.lang.NullPointerException
:
界面:
public interface MyListener {
public void listen();
}
创建事件的活动:
public class Activity2 extends Activity {
private MyListener myListener;
public void setUpListener(MyListener myListener) {
this.myListener = myListener;
}
private void doWork(){
//do stuff
myListener.listen();
}
}
完成工作后我想在该事件中获得的活动:
Activity where I'd like to get that event when work is done:
public class Activity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity2 activity2 = new Activity2();
activity2.setUpListener(new setUpListener() {
@Override
public void listen() {
// get the event here
}
});
}
}
推荐答案
这绝对不可能.您永远不会自己实例化一个新的活动.您不会同时运行两个活动.
This is absolutely not possible. You never instanciate a new Activity yourself. You will not have two Activities running at the same time.
如果您希望另一个Activity根据您先前的Activity想要做什么,则需要将其添加到Intent中.
If you want another Activity to do something, based on what your previous Activity wants, then you need to add that to your Intent.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("data field", "data value");
startActivity(intent);
如果您希望通过回调实现特定功能,那么您可能会想到片段.这样,您可以运行相同的Activity,并且可以告诉各个Fragment他们需要做什么.
If you want specific functionality through a callback then you might be thinking of Fragments. In this way, you can have the same Activity running and it can tell individual Fragments what they need to do.
这篇关于活动到活动回调侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!