1,封装liveData工具类
```
setContentView(R.layout.activity_test_liva_data_bus);
LiveDataBus.getInstance().with("data",String.class)
.observe(this, new Observer() {
```
public class TestLiveDataBus {
//存放订阅者
private Map>bus;
private TestLiveDataBus(){
bus =new HashMap<>();
}
private static TestLiveDataBusliveDataBus =new TestLiveDataBus();
public static TestLiveDataBusgetInstance(){
return liveDataBus;
}
//注册订阅者
public MutableLiveDatawith(String key,Class type){
if (!bus.containsKey(key)){
bus.put(key,new MutableLiveData());
}
return (MutableLiveData)bus.get(key);
}
}
2.在A activity 中发送消息
LiveDataBus.getInstance().with("data",String.class).setValue("danny");
3.在B activity 中使使用获取消息
public class TestLivaDataBusActivityextends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_liva_data_bus);
LiveDataBus.getInstance().with("data",String.class)
.observe(this, new Observer() {
@Override
public void onChanged(String s) {
Toast.makeText(TestLivaDataBusActivity.this,s,Toast.LENGTH_SHORT).show();
}
});
}
}
4.就是这么简单 学会了吗!
网友评论