这个是关于eventbus的基本使用小白可以模仿写:
这里需要一个eventbus.jar包
可以去相关地方下,很多都可以下到
代码如下:
activity_main:
FirstEvent.java:
package com.example.tryeventbus_simple;
public class FirstEvent { private String mMsg;
public FirstEvent(String msg) {
// TODO Auto-generated constructor stub
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
MainActivity:
package com.example.tryeventbus_simple;
import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity { Button btn;
TextView tv;
private String mMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
btn = (Button) findViewById(R.id.btn_try);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EventBus.getDefault().post(
new FirstEvent("收到消息"));
}
});
}
//注意如果是studio项目 这里一点加上
@Subscribe
public void onEventMainThread(FirstEvent event) {
String msg = event.getMsg();
Log.d("harvic", msg);
tv.setText(msg);
}
@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
【Android EventBus 基本使用】