Android ViewModel与LiveData整合的目的就是既实现了UI与数据处理的分离,又能及时监听数据的改变,类似于接口监听回调的作用,但是更加安全高效,如果不知道AndroidViewModel的用法,可以参考此示例学习ViewModel,点击此处进入:AndroidViewModel的介绍与使用
下面来学习一下ViewModel吧!主要用到了MutableLiveData这个对象,我们定义一个MyViewModel,代码如下:
public class MyViewModel extends AndroidViewModel { //共享数据 private MutableLiveData<Integer> currentNum; public MyViewModel(@NonNull Application application) { super(application); } public MutableLiveData<Integer> getCurrentNum(){ if(currentNum == null) currentNum = new MutableLiveData<Integer>(); return currentNum; } }
在MainActivity类里面添加一个按钮,给tv_number1设置值,然后观察tv_number2的值变化,代码如下:
public class MainActivity extends AppCompatActivity { private TextView tv_number1,tv_number2; private Button btn_add; private int number_one = 0; private MyViewModel myViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_number1 = findViewById(R.id.tv_number1); tv_number2 = findViewById(R.id.tv_number2); btn_add = findViewById(R.id.btn_add); btn_go = findViewById(R.id.btn_go); myViewModel = new ViewModelProvider(this).get(MyViewModel.class); //观察tv_number2的值变化 myViewModel.getCurrentNum().observe(this, new Observer<Integer>() { @Override public void onChanged(Integer integer) { if(tv_number2 != null) tv_number2.setText("数值(二):"+integer); } }); //设置tv_number1的值 btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { number_one++; tv_number1.setText("数值(一):"+number_one); myViewModel.getCurrentNum().setValue(number_one); } }); } }
效果如图所示,给tv_number1设置值,tv_number2也会跟着变化,并且tv_number2的值不会随着横竖屏切开而导致清空掉:
横屏切换之后,他们的值变化,如图所示:
LiveData扩展知识:
Public constructors | |
---|---|
LiveData() |
Public methods | |
---|---|
T | getValue() Returns the current value. |
boolean | hasActiveObservers() Returns true if this LiveData has active observers. |
boolean | hasObservers() Returns true if this LiveData has observers. |
void | observe(LifecycleOwner owner, Observer<T> observer) Adds the given observer to the observers list within the lifespan of the given owner. |
void | observeForever(Observer<T> observer) Adds the given observer to the observers list. |
void | removeObserver(Observer<T> observer) Removes the given observer from the observers list. |
void | removeObservers(LifecycleOwner owner) Removes all observers that are tied to the given |