天天看點

Android自帶的底部導航欄中Activity與子片段的傳值利用viewmodel進行activity與fragment之間傳值

利用viewmodel進行activity與fragment之間傳值

本人畢業設計選的是基于android開發一個平台,但我的專業并不是學習開發android,是以也算是從頭學起(小白),寫這個隻是為了記錄自己開發過程的一些小難題(大難題我也是請教大佬)。

開始

首先利用android studio建立一個自帶的底部導航欄

Android自帶的底部導航欄中Activity與子片段的傳值利用viewmodel進行activity與fragment之間傳值

運作效果就是

Android自帶的底部導航欄中Activity與子片段的傳值利用viewmodel進行activity與fragment之間傳值

在activity中傳輸資料到fragment中

主要是通過viewmodel(android小白的話可以去了解一下MVVM),以Dashboard為例;

在DashFragment的onCreateView方法裡面

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                new ViewModelProvider(getActivity()).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        TextView textView = root.findViewById(R.id.text_dashboard);
        textView.setText(dashboardViewModel.getText().getValue());
        dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }

        });
        return root;
    }
}`
           

注意的是dashboardViewModel =new ViewModelProvider(getActivity()).get(DashboardViewModel.class),初始的時候填寫的是this。再到Mainactivity中

viewModel=new ViewModelProvider(this).get(DashboardViewModel.class);
        viewModel.mText.setValue("nid");
           

還有一點在DashboardViewmodel中修改了一些東西

public class DashboardViewModel extends ViewModel {

    public MutableLiveData<String> mText= new MutableLiveData<>();;

    public DashboardViewModel() {

    }
    public  void setText(String s)
    {
        mText.setValue(s);
    }

    public LiveData<String> getText() {
        return mText;
    }

}
           

最後效果

Android自帶的底部導航欄中Activity與子片段的傳值利用viewmodel進行activity與fragment之間傳值

第一次進行創作,繼續努力。。。