zoukankan      html  css  js  c++  java
  • 第三方库EventBus消息传递的使用

    个人学习,仅供菜鸟们学习!

    实例:

    首先添加依赖:

    //EventBus依赖
    compile 'org.greenrobot:eventbus:3.0.0'
    然后创建布局:

    然后创建activity消息类

    创建MainActivity

    package com.fuicuiedu.xc.eventbus_20170307;

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.greenrobot.eventbus.EventBus;
    import org.greenrobot.eventbus.Subscribe;
    import org.greenrobot.eventbus.ThreadMode;

    public class MainActivity extends AppCompatActivity {

    TextView mTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //EventBus在监听事件模块完成注册
    EventBus.getDefault().register(this);

    mTv = (TextView) findViewById(R.id.main_tv);

    findViewById(R.id.mian_btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
    startActivity(intent);
    }
    });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void aaa(MessageEvent messageEvent){
    String msg = messageEvent.getMsg();
    //弹吐司
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    //更新UI
    mTv.setText(msg);
    }

    @Override
    protected void onDestroy() {
    super.onDestroy();
    //取消订阅,反注册
    EventBus.getDefault().unregister(this);
    }
    }

    跳转页面:

    package com.fuicuiedu.xc.eventbus_20170307;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;

    import org.greenrobot.eventbus.EventBus;

    public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    findViewById(R.id.second_btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    //发送事件
    EventBus.getDefault().post(new MessageEvent("面对疾风吧!"));
    }
    });
    }
    }

    完毕!!!项目名称

    
    
    
  • 相关阅读:
    CTK 编译
    MITK 2021.2编译
    执行git add .报错LF will be replaced by CRLF in
    vscode标记“&&”不是此版本中的有效语句分隔符
    vscode prettier插件使用无效
    vscode使用技巧
    kafka及hdfs常用命令
    博客已迁移
    SVM
    逻辑回归
  • 原文地址:https://www.cnblogs.com/ll-ouyang/p/6513995.html
Copyright © 2011-2022 走看看