1. 程式人生 > 其它 >jetpack----Navigation元件(導航) 讓頁面切換無比簡單 03 更好的傳值方式

jetpack----Navigation元件(導航) 讓頁面切換無比簡單 03 更好的傳值方式

這張圖很重要,講了ViewModel能全域性的在activity或者fragment傳值

例子:拖動seekbar,在textview顯示數字,點選按鈕,把seekbar現在的數字帶到下一個頁面

想繫結資料,別忘了這行程式碼

dataBinding{
        enabled true
    }

然後點一下小燈泡改變佈局,寫資料

老規矩,寫ViewModel

package com.example.navviewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel { private MutableLiveData<Integer> number; public MutableLiveData<Integer> getNumber() { if (number == null){ number = new MutableLiveData<>(); number.setValue(0); } return number; }
public void add(int x){ if (number.getValue() < 0){ number.setValue(0); } number.setValue(number.getValue()+x); } }

建立兩個fragment,然後建立Navigation資原始檔,把兩個fragment新增進來,該連線的連線,該點小房子的點小房子。

MasterFragment。 主介面
package com.example.navviewmodel;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import com.example.navviewmodel.databinding.MasterFragmentBinding; public class MasterFragment extends Fragment { private MyViewModel mViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mViewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class); MasterFragmentBinding binding; //fragment載入佈局 binding = DataBindingUtil.inflate(inflater,R.layout.master_fragment,container,false); binding.setData66(mViewModel); binding.setLifecycleOwner(getActivity()); //activity是this fragment是getActivity,獲取所依附的Activity //切換頁面 點選按鈕跳轉到另一個fragment binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
          //navigate是導航的意思,通過導航控制去導航 NavController controller
= Navigation.findNavController(view); controller.navigate(R.id.action_masterFragment_to_detailFragment); } }); //SeekBar(拖動條) 對拖動條的監聽 binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { mViewModel.getNumber().setValue(i); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); return binding.getRoot(); } }

DetailFragment
package com.example.navviewmodel;

import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.navviewmodel.databinding.FragmentDetailBinding;


public class DetailFragment extends Fragment {

    public DetailFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //獲取ViewModel
        MyViewModel myViewModel;
        myViewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
        //獲得雙向繫結
        FragmentDetailBinding binding;
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_detail,container,false);
        //繫結資料和宣告週期
        binding.setData66(myViewModel);
        binding.setLifecycleOwner(getActivity());

        return binding.getRoot();
    }

}
MasterFragment
<?xml version="1.0" encoding="utf-8"?>
<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="data66"
            type="com.example.navviewmodel.MyViewModel" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MasterFragment">

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

            <TextView
                android:id="@+id/textView3"
                android:layout_width="244dp"
                android:layout_height="131dp"
                android:text="@{String.valueOf(data66.number)}"
                android:textAlignment="center"
                android:textSize="48sp"
                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.198" />

            <SeekBar
                android:id="@+id/seekBar"
                android:layout_width="0dp"
                android:layout_height="20dp"
                android:max="100"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView3"
                app:layout_constraintVertical_bias="0.306" />

            <Button
                android:id="@+id/button"
                android:layout_width="194dp"
                android:layout_height="102dp"
                android:text="Button"
                tools:layout_editor_absoluteX="124dp"
                tools:layout_editor_absoluteY="504dp"
                tools:ignore="MissingConstraints" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </FrameLayout>
</layout>