欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【android学习】Jetpack:LiveData共享数据

程序员文章站 2022-06-08 15:53:52
...

简介

前面讲解了LiveData的简单使用Jetpack:LiveData的简单使用,这里主要讲解livedata的数据共享

我们这里使用LiveData进行两个fragment之间通信,达到如下效果

【android学习】Jetpack:LiveData共享数据

先看ViewModel类

public class NameViewModel extends ViewModel {

    //liveData通常和viewModel一起使用
    private  MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getmCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<String>();
        }
        return mCurrentName;
    }

    //如果需要可以在这里释放资源
    @Override
    protected void onCleared() {
        super.onCleared();
    }
}

发送端的fragment

这里点击发送按钮,给NameViewModel 中发送edittext中填入的值

public class FragmentOne extends Fragment {

    private EditText edContent;
    private Button btnSend;
    NameViewModel model;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        edContent = view.findViewById(R.id.et_content);
        btnSend = view.findViewById(R.id.btn_send);

        //获取viewModel
        model = ViewModelProviders.of(getActivity()).get(NameViewModel.class);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取到liveData后设置liveData的值
                model.getmCurrentName().setValue(edContent.getText().toString());
            }
        });
        return view;
    }

}

接收端fragment

这里通过对NameViewModel 的监听,实现对FragmentOne中的edittext值变化的监听

public class FragmentTwo extends Fragment {


    private TextView textName;
    private NameViewModel model;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        textName = view.findViewById(R.id.tv_text);

        //获取viewModel
        model = ViewModelProviders.of(getActivity()).get(NameViewModel.class);
        //监听值的变化
        //model.getmCurrentName().observeForever();可以在任何时候得到数据
        model.getmCurrentName().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //更新UI
                textName.setText(s);
            }
        });
        return view;
    }

}

 

我们再看一下activity之间的传值

我们点击第一个activity跳转到第二个activity,在第二个activity中,输入值,设置给MutableLiveData,点击返回,在第一个activity中,监听第二个activity转过来的值

【android学习】Jetpack:LiveData共享数据

因为ViewModel是个activity生命周期相匹配的,所以我们需要修改一下MutableLiveData为static

    private static MutableLiveData<String> mCurrentName;

监听值activity

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mTextTv;
    private NameViewModel model;
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        initView();
        //获取viewModel
        model = ViewModelProviders.of(this).get(NameViewModel.class);
        //监听值的变化
        //model.getmCurrentName().observeForever();可以在任何时候得到数据
        model.getmCurrentName().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //更新UI
                mTextTv.setText(s);
            }
        });
    }

    private void initView() {
        mTextTv = (TextView) findViewById(R.id.tv_text);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                // TODO 19/10/12
                startActivity(new Intent(this,FirstActivity.class));
                break;
            default:
                break;
        }
    }
}

设置值的activity

public class FirstActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mContentEt;
    private Button mSendBtn;
    private NameViewModel model;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_one);
        initView();
        //获取viewModel
        model = ViewModelProviders.of(this).get(NameViewModel.class);
    }

    private void initView() {
        mContentEt = (EditText) findViewById(R.id.et_content);
        mSendBtn = (Button) findViewById(R.id.btn_send);
        mSendBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                //获取到liveData后设置liveData的值
                model.getmCurrentName().setValue(mContentEt.getText().toString());
                break;
            default:
                break;
        }
    }
}

这样,就可以避免使用intent 或者startActivityForResult传值,就可以达到数据传递共享

相关标签: livedata