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

后端 未结 4 1917
北荒
北荒 2020-12-19 20:47

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 act

相关标签:
4条回答
  • 2020-12-19 21:28

    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.

    0 讨论(0)
  • 2020-12-19 21:39

    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.

    0 讨论(0)
  • 2020-12-19 21:41

    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();
    
    0 讨论(0)
  • 2020-12-19 21:49

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

    0 讨论(0)
提交回复
热议问题