zoukankan      html  css  js  c++  java
  • EventBus学习

    Git位置https://github.com/greenrobot/EventBus

    使用起来很方便:
    1. Implement any number of event handling methods in the      subscriber:
         public void      onEvent(AnyEventType event) {}
    2. Register subscribers:
         eventBus.register(this);
    3. Post events to the bus:
         eventBus.post(event);
    4. Unregister subscriber:
         eventBus.unregister(this);

    5. public void onEventMainThread(EventType event)方法

    两个Activity直接的使用

    在第一个Activity的Code如下:

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            EventBus.getDefault().register(this);
            textView = (TextView)findViewById(R.id.textView);
            Button btn_try = (Button)findViewById(R.id.btn_try);
            btn_try.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getApplicationContext(),
                            SecondActivity.class);
                    startActivity(intent);
                }
            });
        }
    
        @Subscribe
        public  void onEventMainThread(EventType event){
            textView.setText(event.getMessage());
            Toast.makeText(this,event.getMessage(),Toast.LENGTH_LONG).show();
        }

    OnDestory方法

      @Override
        protected void onDestroy() {
            super.onDestroy();
            EventBus.getDefault().unregister(this);
        }

    在第二个Activity中使用

     Button btn_first_event = (Button)findViewById(R.id.btn_first_event);
            btn_first_event.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new EventType("FistEvent btn cliced"));
                }
            });

    具体实现可参考。

    1、《EventBus使用详解(一)——初步使用EventBus》

    2、《EventBus使用详解(二)——EventBus使用进阶》

    其它参考:

    《Android解耦库EventBus的使用和源码分析》:http://blog.csdn.net/yuanzeyao/article/details/38174537

    原理很重要哦。

    《EventBus的使用初试》:http://blog.csdn.net/pp_hdsny/article/details/14523561

    《EventBusExplained  》:https://code.google.com/p/guava-libraries/wiki/EventBusExplained

    《Google Guava EventBus实例与分析》

  • 相关阅读:
    5
    4
    2
    3
    1
    IOS js交互
    vm安装mac
    索引
    ORM 基础
    reids 日志no
  • 原文地址:https://www.cnblogs.com/linlf03/p/4724670.html
Copyright © 2011-2022 走看看