美文网首页
Otto快速使用

Otto快速使用

作者: 黄晓果 | 来源:发表于2017-12-13 12:16 被阅读0次

    引入 otto

     compile 'com.squareup:otto:1.3.8'
    

    1、创建AppBus单例,提高效率

    package tsou.cn.ottotest;
    
    import com.squareup.otto.Bus;
    
    /**
     * Created by 黄家三少 on 2017/12/12.
     */
    
    public class AppBus extends Bus {
    
        private static AppBus bus;
    
        private AppBus() {
        }
    
        public static AppBus getInstance() {
            if (bus == null) {
                bus = new AppBus();
            }
            return bus;
        }
    }
    
    

    2、创建数据类(因为otto没有EventBus的tag标记功能)

    package tsou.cn.ottotest.ottobean;
    
    /**
     * Created by Administrator on 2017/12/13 0013.
     */
    
    public class PlusOneText {
        public PlusOneText(String name) {
            this.name = name;
        }
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    

    3、在数据接收页面—订阅,取消订阅,接收数据

      AppBus.getInstance().register(this);
    
      AppBus.getInstance().unregister(this);
    
        @Subscribe
        public void showToast(OttoBean ottoBean) {
            Toast.makeText(getContext(), ottoBean.getName() + ",===" + ottoBean.getAge(), Toast.LENGTH_LONG).show();
    //        mText.setText(ottoBean.getName());
        }
    
        @Subscribe
        public void setContext(PlusOneText plusOneText) {
            mText.setText(plusOneText.getName());
        }
    

    4、在数据传送的地方—发送数据

    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_one:
                    OttoBean ottoBean = new OttoBean();
                    ottoBean.setName("黄晓果");
                    ottoBean.setAge(25);
                    AppBus.getInstance().post(ottoBean);
                    finish();
                    break;
                case R.id.button_two:
                    AppBus.getInstance().post(new PlusOneText("huangxiaoguo"));
                    finish();
                    break;
            }
        }
    

    相关文章

      网友评论

          本文标题:Otto快速使用

          本文链接:https://www.haomeiwen.com/subject/szeaixtx.html