Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - Android - Calling a method in one activity from another, without starting new activity

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

public class ActivityBase extends Activity
{
public void showToast()
{
...

Then your activities derive from this

public class MyActivity extends ActivityBase
{
public void someMethod()
{
showToast();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...