首页 > 其他分享 >Livedata+viewmodel+Fragment

Livedata+viewmodel+Fragment

时间:2023-04-23 18:56:18浏览次数:42  
标签:ViewModel Fragment viewmodel LiveData SeekBar Livedata progress public

title:LiveData viewmodel 实现Fragment间的通信

使用ViewModel+LiveData实现同一个Activity不同Fragment间的通信。

1.将两个Fragment等比例放置在Activity的布局文件中。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/one_fragment"
        android:name="com.test.mytest.OneFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@id/two_fragment"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/two_fragment"
        android:name="com.test.mytest.TwoFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/one_fragment" />

2.定义Livedata和ViewModel

public class ShareDataViewModel extends ViewModel
{
    private MutableLiveData<Integer> progress;

    public LiveData<Integer> getProgress()
    {
        if (progress == null)
        {
            progress = new MutableLiveData<>();
        }
        return progress;
    }

    @Override
    protected void onCleared()
    {
        super.onCleared();
        progress = null;
    }
}

3.编写Fragment的代码,实现具体的通信。这里以OneFragment为例,TwoFragment也是类似的代码。

public class OneFragment extends Fragment
{
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View parentView = inflater.inflate(R.layout.fragment_one, container, false);
        final SeekBar seekBar = parentView.findViewById(R.id.seekBar);

//注意:这里ViewModelProviders.of(getActivity())这里的参数需要是Activity,而不能是Fragment,否则收不到监听
        final ShareDataViewModel shareDataViewModel = ViewModelProviders.of(getActivity()).get(ShareDataViewModel.class);
        final MutableLiveData<Integer> liveData = (MutableLiveData<Integer>)shareDataViewModel.getProgress();
        //通过observe方法观察ViewModel中字段数据的变化,并在变化时,得到通知
        liveData.observe(this, new Observer<Integer>()
        {
            @Override
            public void onChanged(@Nullable Integer progress)
            {
                seekBar.setProgress(progress);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
            {
                //用户操作SeekBar时,更新ViewModel中的数据
                liveData.setValue(progress);
            }
        });
        return parentView;
    }
}

4.在Fragment的布局文件中放置一个SeekBar控件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_above="@+id/seekBar"
        android:text="Fragment_One"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:max="100"
        android:layout_centerInParent="true"/>

</RelativeLayout>

可以看到,无论是滑动OneFragment还是TwoFragment中的SeekBar,另外一个Fragment中的SeekBar也会跟着滑动。滑动SeekBar时,通过LiveData.setValue(),修改了ViewModel中LiveData包装的数据(progress字段)。由于Fragment通过LiveData.observe()方法,监听了数据的变化,所以progress字段被修改后,Fragment能够第一事件收到通知,进而更新UI。这就是利用ViewMode和LiveData实现Fragment间通信的原理。另外,从演示图中,我们还能看到,屏幕旋转后SeekBar的进度与旋转前保持一直,数据并未丢失,这也是ViewModel带来的好处之一。

标签:ViewModel,Fragment,viewmodel,LiveData,SeekBar,Livedata,progress,public
From: https://www.cnblogs.com/ZZXJJ/p/17347441.html

相关文章

  • Vue3 Fragment
    视频五、新的组件1.Fragment在Vue2中:组件必须有一个根标签在Vue3中:组件可以没有根标签,内部会将多个标签包含在一个Fragment虚拟元素中好处:减少标签层级,减小内存占用......
  • fragment
    title:Fragment碎片的静态注册每个碎片都有对应的XML布局文件,依据其使用方式可分为静态注册与动态注册两类。静态注册指的是在XML文件中直接放置fragment节点,类似于一个普通控件,可被多个布局文件同时引用。静态注册一般用于某个通用的页面部件(如Logo条、广告条等),每个活动页面......
  • ViewPager2+Fragment+FragmentStateAdapter遇到系统主题更换时Fragment数据丢失
    1.问题描述:在ViewPager设置壁纸,导致Activity获取Fragment数据丢失2.解决方案:设置 vp.isSaveEnabled=false  ,设置不保存,在适配器中销毁item 引发问题:vp重建之后,会丢失之前所在的位置解决方案:Activity onSaveInstanceState中保存数据,在 o......
  • Fragment——底部导航栏的实现
    本节开始我们会讲解一些Fragment在实际开发中的一些实例!而本节给大家讲解的是底部导航栏的实现!而基本的底部导航栏方法有很多种,比如全用TextView做,或者用RadioButton,又或者使用TabLayout+RadioButton,当然复杂的情况还是得走外层套布局的方法!本节我们用TextView来做一个底部导航栏......
  • Activity向fragment传入数值
    因项目需要activity向fragment传值,搜索了很久,看了一些书,实现了代码:我传入的是一个int类型值activity(menu)staticintUser_id;//没有static会置0,具体原因不清楚publicintgetUser_id(){returnUser_id;}publicvoidsetUser_id(intuser_id){User_id......
  • Android studio 中fragment 的简单应用
    在AndroidStudio中,Fragment是一种可重用的UI组件,它代表了Activity中的一部分界面。它类似于Activity,但是可以被添加、删除和替换,同时可以与其他Fragment组合在一起形成更复杂的UI界面。通常情况下,Activity由多个Fragment组成,每个Fragment都有自己的布局和功能,可......
  • fragment里导入listview
    Fragment中使用listview的用法文章目录Fragment中使用listview的用法1、定义xml1.1fragment_my.xml1.2my_menu.xml1.3Fragment核心代码1.4测试背景:在android项目中,经常用到关于listview的,经过很多博客博主的文章,我尝试很多测试都失败了,终于通过不断的总结调试终于有了可靠的......
  • Activity发送信息给Fragment
    在MainActivity中设置发送的信息,在fragment中接收,@OverridepublicvoidonClick(Viewview){switch(view.getId()){caseR.id.btn:Bundlebundle=newBundle();bundle.putString("message","我喜欢学习");Blan......
  • Fragment动态添加与管理
    activity_main.xml<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools=&quo......
  • Android LiveData Transformations怎么使用
    AndroidLiveDataTransformations是LiveData库中的一个类,它提供了一些便捷的方法来转换LiveData的数据。使用LiveDataTransformations需要在项目的build.gradle文件中添加以下依赖项: implementation'androidx.lifecycle:lifecycle-extensions:2.2.0'接下来可以在Vi......