Communication between nested fragments in Android

前端 未结 4 1256
无人共我
无人共我 2020-12-07 17:00

I recently learned how to make nested fragments in Android. I don\'t know how communication is supposed to happen, though.

From reading the fragment commun

4条回答
  •  被撕碎了的回忆
    2020-12-07 17:53

    Although @Suragch's answer is correct, But I want to add another way to pass data between Fragments or Activity. No matter it's an Activity or Fragment you can pass data with event bus in 3 steps:

    1- Define an event(message):

    public class OrderMessage {
        private final long orderId;
        /* Additional fields if needed */
        public OrderMessage(long orderId) {
            this.orderId = orderId;
        }
        public long getOrderId() {
            return orderId;
        }
    }
    

    2- Register and Unregister for Events: To be able to receive events, the class must register/unregister for event bus. The best place for Activities and Fragments is onStart() and onStop()

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    

    To be able to receive an event you have to subscribe to that event. To do that, add @Subscribe annotation to one of your methods in your class.

    @Subscribe(threadMode = ThreadMode.MAIN)
       public void onMessage(OrderMessage message){
           /* Do something for example: */
           getContractDetails(message.getOrderId());
       }
    

    3- Post an event

    EventBus.getDefault().post(new OrderMessage(recievedDataFromWeb.getOrderId()));
    

    More documentation and examples could be found Here. There are also other libraries like : Otto

提交回复
热议问题