Search code examples
mvvmcrosscomposite-view

MVVMCross 4.1.4 Composite Views


Iam currently trying to implement composite views in my app for the tablet layout, so i dont need the Viewpager and TabLayout which is used in the phone layout.

But apparently it is not as easy as i thought it would be and the examples/tutorials which i found are made for the older version of MVVMCross.

My idea was just to search for the viewpager, if it is not found in the current layout, then check for the framelayouts and show my two different viewmodels like i did with the MvxFragmentPagerAdapter for the Viewpager/Tablayout.

Is there any "clean" solution for this?

Thank you for you time!


Solution

  • I found a acceptable answer by using FragmentTransactions. Here is the simplified code. Though iam kinda abusing the MvxFragmentPagerAdapter.GetItem(index) here for the Fragment and ViewModel Initialization (https://github.com/MvvmCross/MvvmCross-AndroidSupport/blob/master/MvvmCross.Droid.Support.V4/MvxFragmentPagerAdapter.cs) :

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = base.OnCreateView(inflater, container, savedInstanceState);
            var viewPager = view.FindViewById<ViewPager>(Resource.Id.viewpager);
            var fragments = new List<MvxFragmentPagerAdapter.FragmentInfo> {
              new MvxFragmentPagerAdapter.FragmentInfo("Fragment1", typeof(FragmentOne),
               typeof(FragmentViewModelOne)),
              new MvxFragmentPagerAdapter.FragmentInfo("Fragment2", typeof(FragmentTwo),
               typeof(FragmentViewModelTwo))
             };
            var adapter = new MvxFragmentPagerAdapter(Activity, ChildFragmentManager, fragments);
            if (viewPager != null)
            {
                viewPager.Adapter = adapter;
                var tabLayout = view.FindViewById<TabLayout>(Resource.Id.tabs);
                if (tabLayout != null)
                {
                    tabLayout.SetupWithViewPager(viewPager);
                }
            }
            else
            {
                FragmentTransaction transaction = FragmentManager.BeginTransaction();
                transaction.Replace(Resource.Id.frameone, adapter.GetItem(0), "Fragment1");
                transaction.Replace(Resource.Id.frametwo, adapter.GetItem(1), "Fragment2");
                transaction.Commit();
            }
            return view;
        }
    

    If there is a better solution, dont be shy! =)

    Greetings Cyriac