androidx.lifecycle.MutableLiveData的使用

相关链接:带你深入了解官方架构组件LiveData

基本概念

MutableLiveData可以方便处理:数据变化 ——> xxx更新

使用步骤:(哪一步放在哪,视情况而定)

1.定义 MutableLiveData属性

2.为属性绑定一个 observer

3.设置属性的值

示例及解析

package com.clc.app39;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private MutableLiveData<String> mName = new MutableLiveData<>();

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

        /*
         * bind an observer to "mName"
         * param1 controls the observer`s lifecycle
         * parem2 observes change of "mName",and calls onChanged()
         */
        mName.observe(this, new Observer<String>() {
            //param "s" is value after mName.setValue("name1")
            @Override
            public void onChanged(String s) {
                //You can update UI text here
                TextView textView = findViewById(R.id.text_view);
                textView.setText(s);
            }
        });

        /*
         * call setValue() where needed
         * Sets the value. If there are active observers, the value will be dispatched to them.
         * This method must be called from the main thread.
         * If you need set a value from a background thread, you can use postValue(Object)
         */
        mName.setValue("name1");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38861828/article/details/103734016