JetPack_LiveData的基本使用

2020-08-26  本文已影响0人  遇见开始遇见

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.就是这么简单 学会了吗!

上一篇下一篇

猜你喜欢

热点阅读