开发者

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.

开发者_如何学Python

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


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();


Right. If the method is static, which it probably should be if this is your goal, just call it like this:

YourClass.staticMethod(params);

If not, you'll need to create an object for it.

YourClass yourClass = new YourClass(constructorParams);
yourClass.method(params);

That should do it.


I m not sure about your question but try like this may be it will work

((MainActivity) activity).textViewSetText();

public void textViewSetText (String value){

    tv.setText(value);    
}

but your activity have to extends The MainActivity.


In addition to the static method, you can not call any methods which in another activity!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜