Android - 从一个活动调用另一个活动中的方法,而不启动新活动
我正在使用 GreenDroid 开发 Android 应用程序。该应用程序仅用于测试 atm,因此它包含一个带有刷新按钮的 ActionBar、三个选项卡以及每个选项卡的活动。
我此刻想要实现的就是在 ActionBar 上按下刷新按钮时显示一条 toast 消息,但我希望从我的一个活动中调用 toast 消息,我们将其称为 Listener1Activity,它是位于第一个选项卡中的活动...这是因为 Listener1Activity 最终将包含一个我想要在按下 ActionBar 按钮时重新加载的列表,如果我现在可以让它使用简单的 toast 消息,那么我可以解决这个问题之后。
我研究了意图、广播,但似乎没有什么合适的。
我不希望每次按下按钮时活动都重新启动,我只想其中有一个方法来调用并显示 toast。
所以基本上,这就像同时运行 2 个活动,按下一个活动中的按钮,调用另一个活动中的方法。不是吗?还是我弄错了?
SenderActivity 和 Listener1Activity。
在 iOS 中,我只需从 SenderActivity 发送 NSNotification,并在 Listener1Activity 中添加观察者。在 Android 中实现这一目标的最佳方法是什么?
谢谢!
史蒂文
I'm developing an Android app using GreenDroid. The application is just for testing atm, so it all it contains is an ActionBar with a refresh button, three tabs, and an activity for each of those tabs.
All I'm trying to achieve at the minute is showing a toast message when the refresh button is pressed on the ActionBar, but I want the toast message to be called from within one of my activities, we'll call it Listener1Activity which is the activity that sits in the first tab ... this is because Listener1Activity will eventually contain a list that I want to reload when the ActionBar button is pressed, if I can get it working with a simple toast message for now then I can sort out that later.
I've looked into intents, broadcasts, but nothing seems to fit.
I don't want the activity starting new each time the button is pressed, I just want a method in it to call and show the toast.
So basically, it's just like having 2 activities running at the same time, and a button press in one calling a method in the other. Isn't it? Or have I got that wrong?
SenderActivity and Listener1Activity.
In iOS, I would just send an NSNotification from SenderActivity, and add an observer in Listener1Activity. What would be the best way to achieve this in Android?
Thanks!
Steven
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不希望实例化其他 Activity,则该方法不适合该位置。如果它是多个活动之间的共享功能,为什么不为派生自活动的活动创建一个基类。
那么你的活动就源于此
If you don't want the other Activity instantiated, then that's not the place for this method. If it's shared functionality between more than one Activity, why not create a base class for your activities that derives from Activity.
Then your activities derive from this
正确的。如果该方法是静态的(如果这是您的目标,则可能应该是静态的),只需这样调用它:
如果不是,您将需要为其创建一个对象。
应该可以做到这一点。
Right. If the method is static, which it probably should be if this is your goal, just call it like this:
If not, you'll need to create an object for it.
That should do it.
我不确定你的问题,但尝试这样可能会起作用,
但你的活动必须扩展 MainActivity。
I m not sure about your question but try like this may be it will work
but your activity have to extends The MainActivity.
除了静态方法之外,您不能调用其他活动中的任何方法!
In addition to the static method, you can not call any methods which in another activity!