How to call a method in another activity

前端 未结 2 344
心在旅途
心在旅途 2020-12-18 06:32

I have a question about communication between activities on implementation program of Android.

Here is two activity classes.

public class HelloAndroi         


        
相关标签:
2条回答
  • 2020-12-18 06:50

    although you can do it by creating static method , but not right way because it will leave context . pass data to Tab1Activity you have in HelloAndroidActivity throgh intent . inside Tab1Activity getIntent and work accordingly .

    you can also use onTabChange() to reflect changes between tabs .

    0 讨论(0)
  • 2020-12-18 06:59

    You can pass data between activities using intent, you could put it in the extras with the intent:

    HelloAndroidActivity

    intent.putExtra("callX", true);
    

    Tab1Activity

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        boolean callX = extras.getBoolean("callX");
        if(callX) {
           X();
        }
    }
    

    EDIT If you need to event/listener mechanism it could be roughly like this(haven't compiled this, but should give you an idea):

    public inerface MyEventListener {
        abstract void handleMyEvent();
    }
    
    public class Tab1Activity implements MyEventListener {
    
        public void handleMyEvent() {
            /*...*/
        }
    
        protected void onCreate(Bundle savedInstanceState) {
             /*...*/
             HelloAndroidActivity.addListener(this);
        }
    
        protected void  onDestroy() {
             /*...*/
             HelloAndroidActivity.removeListener(this);
        }
    }
    
    
    public class HelloAndroidActivity {
        static ArrayList<MyEventListener> listeners = new ArrayList<MyEventListener>();
        public static void addListener(MyEventListener listener) {
            listeners.add(listener);
        }
        public static void removeListener(MyEventListener listener) {
            listeners.remove(m);
        }
    
        public static void onEvent() {
            for(MyEventListener m : listeners) {
                m.handleMyEvent();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题