The use of Eventbus in Android development

Source: Internet
Author: User

1.EventBus use of values in activity (Observer mode):

It is divided into three steps. 1. event occurrence 2. Observer (subscription event) 3. The observed or observed object (sending events)

The following is an example of a activty (send event) jump to fragment (subscribe to an event)

First step: Event definition (put data mode)

public String type;
public String content;
Public String GetType () {
return type;
}

public void SetType (String type) {
This.type = type;
}

Public String getcontent () {
return content;
}

public void SetContent (String content) {
this.content = content;
}

Step Two: Send events

/Instantiating a Fragment object
Upfragment upfragment = new Upfragment ();
Get the Shard Manager
Fragmentmanager manager = OneActivity.this.getFragmentManager ();
Get transactions
Fragmenttransaction transaction = Manager.begintransaction ();

adding fragments to the activity, r.id.left refers to the ID of the layout in the activity
Transaction.replace (R.id.ll_one, upfragment);
Submit
Transaction.commit ();
Eventbus.getdefault (). Post (New MyEvent ());

Step three: Subscribe to events:

Register in the Oncreat () method: Eventbus.getdefault (). Register (this);

Unregister in the Ondestory () method: Eventbus.getdefault (). Unregister (this);

The most important method:

  Receive data (OnEvent is in jar package)
public void Oneventmainthread (MyEvent event) {
LOG.E ("1", "" "+ event.getcontent ());
Tvres.settext ("received message:" + Event.gettype ());
}

In addition, fragment to fragment data, but subscribe to the event is put in all fragment activity.

The use of Eventbus in Android development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.