EventBus使用

//导入依赖

compile 'org.greenrobot:eventbus:3.1.1'

    在接受的方法里注册和反注册  
      
    //注册EventBus  
    EventBus.getDefault().register(this);  
      
    onDestory方法里反注册  
    EventBus.getDefault().unregister(this);//反注册EventBus  
      
      
    在第二个Activity中进行post发送  
    //发送的msg是Object类型  
    EventBus.getDefault().post(Object);  
      
    //eventbus接收消息  
    //得有注解!!!  参数的发送的类型  
    @Subscribe  
    public void onEventMainThread(Object event) {  
        tv.setText(event.toString);  
    }  

//详细代码
//MainActivity


    public class MainActivity extends AppCompatActivity {  
      
        private TextView tv;  
      
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
            EventBus.getDefault().register(this);  
            Button btn= (Button) findViewById(R.id.btn);  
            tv = (TextView) findViewById(R.id.tv);  
            btn.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View view) {  
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);  
                    startActivity(intent);  
                }  
            });  
        }  
        @Subscribe  
        public void onEventMainThread(String event) {  
      
               tv.setText(event);  
            //if (event != null) {  
          // String o= (String) event;  
          // if (o!= 0) {  
          // tv.setText(o);        
             // }  
        //}   
    }  
      @Override protected void onDestroy() {   
           super.onDestroy();   
          EventBus.getDefault().unregister(this);  
      }  
      
    }  

//Main2Activity

public class Main2Activity extends AppCompatActivity {
[java] view plain copy

        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main2);  
            Button btn= (Button) findViewById(R.id.btn);  
            btn.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View view) {  
                    EventBus.getDefault().post("你好");  
                }  
            });  
        }  
    }  

//Mian2Activity布局

      
        

//MainActivity布局

      
      
          
       


你可能感兴趣的:(EventBus使用)