Android---ViewModel实现Fragment跨页面数据共享

前面完成了Navigation实现fragement的切换
在最后,我们提到数值的传递问题。

这篇我们在上一篇的基础上,增加一个ViewModel来实现数据的共享。

直接上代码吧。也不是很难。

首先是两个fragment。要注意的是fragment返回的view对象。

HomeFragment:

public class HomeFragment extends Fragment {

    private MyViewModel viewModel;
    private FragmentHomeBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

        viewModel=new ViewModelProvider(getActivity()).get(MyViewModel.class);

        binding= DataBindingUtil.inflate(inflater,R.layout.fragment_home,container,false);
        binding.setData(viewModel);
        binding.setLifecycleOwner(getActivity());
        binding.btnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController controller=Navigation.findNavController(v);
                controller.navigate(R.id.action_homeFragment_to_blankFragment);
            }
        });

        return binding.getRoot();
//        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}

xml:

<layout 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">

    <data>
        <variable
            name="data"
            type="com.example.myfragment.MyViewModel"/>
    data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".HomeFragment">


        <TextView
            android:id="@+id/tv_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(data.getNumber)}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.2" />

        <Button
            android:id="@+id/btn_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.4" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{()->data.add()}"
            android:text="add"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.278" />

    androidx.constraintlayout.widget.ConstraintLayout>
layout>


BlankFragment:

public class BlankFragment extends Fragment {


    private MyViewModel viewModel;
    private FragmentBlankBinding binding;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        viewModel=new ViewModelProvider(getActivity()).get(MyViewModel.class);
        binding= DataBindingUtil.inflate(inflater,R.layout.fragment_blank,container,false);
        binding.setData(viewModel);
        binding.setLifecycleOwner(getActivity());

        binding.getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), String.valueOf(viewModel.getNumber().getValue()), Toast.LENGTH_SHORT).show();
            }
        });

        return binding.getRoot();
    }
}

xml:

<layout 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">

    <data>
        <variable
            name="data"
            type="com.example.myfragment.MyViewModel"/>
    data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/getBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GET"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    androidx.constraintlayout.widget.ConstraintLayout>
layout>

ViewModel:

public class MyViewModel extends ViewModel {

    private MutableLiveData<Integer> number;

    public MutableLiveData<Integer> getNumber(){
        if(number==null){
            number=new MediatorLiveData<>();
            number.setValue(0);
        }
        return number;
    }

    public void add(){
        number.setValue(number.getValue()+1);
    }

}

完成效果:
Android---ViewModel实现Fragment跨页面数据共享_第1张图片
Android---ViewModel实现Fragment跨页面数据共享_第2张图片

第一个fragment点击增加。第二个fragment点击可以获取到该值。

你可能感兴趣的:(Android)