2

I have a MVP app that I want to migrate to MVVM + Jetpack. Using the Navigation Architecture Component (NAC), my setup now is I have a NavHostActivity and its layout file, activity_nav_host.xml houses a DrawerLayout, a Toolbar and a NavigationView:

<?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"
    xmlns:bind="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="vm"
            type="com.myapp.base.NavHostViewModel"/>
    </data>

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:openDrawer="start"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar_custom"
                bind:vm="@{vm}"/>

            <fragment
                android:id="@+id/fragment_nav_host"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@id/toolbar"
                app:defaultNavHost="true"
                app:navGraph="@navigation/graph"/>
        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_drawer"
            android:layout_width="360dp"
            android:layout_height="match_parent"
            android:layout_gravity="start">

            <ScrollView
                android:id="@+id/scroll_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <include
                    android:id="@+id/drawer_navigation"
                    layout="@layout/drawer_navigation" />
            </ScrollView>

        </com.google.android.material.navigation.NavigationView>
    </androidx.drawerlayout.widget.DrawerLayout>
</layout>

When using the NAC, it's recommended to use one activity and many fragments. In the file above, @+id/fragment_nav_host is the container for those fragments, and for every screen, it's my intention to change the toolbar title accordingly. Here are the contents of the included toolbar (toolbar_custom.xml):

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="vm" type="com.myapp.base.NavHostViewModel"/>
    </data>

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:paddingEnd="16dp"
        android:background="@color/colorPrimary"
        app:contentInsetStartWithNavigation="0dp"
        android:elevation="4dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:background="@android:color/transparent">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@android:color/transparent"
                android:fontFamily="@font/montserrat_bold"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="20sp"
                android:singleLine="true"
                android:ellipsize="end"
                android:text="@={vm.title}"
                tools:text="Title" />
        </RelativeLayout>
    </androidx.appcompat.widget.Toolbar>
</layout>

And the ViewModel for NavHostActivity:

public class NavHostViewModel extends ViewModel {
    public MutableLiveData<String> title = new MutableLiveData<>();

    public NavHostViewModel(String title) {
        this.title.setValue(title);
    }

    static class Factory implements ViewModelProvider.Factory {
        private String title;

        Factory(String title) {
            this.title = title;
        }

        @SuppressWarnings("unchecked")
        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            return (T) new NavHostViewModel(title);
        }
    }
}

Finally, here's NavHostActivity itself:

public class NavHostActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityNavHostBinding binding = 
                DataBindingUtil.setContentView(this, R.layout.activity_nav_host);
        NavHostViewModel viewModel =
                ViewModelProviders.of(this, new NavHostViewModel.Factory("MyApp"))
                        .get(NavHostViewModel.class);
        binding.setVm(viewModel);
        binding.setLifecycleOwner(this);
    }
}

Now, since each fragment screen will have its own title for the toolbar, and the title will come from the ViewModel of that particular fragment, I have that ViewModel extend NavHostViewModel then set the title with a super() call to the parent constructor. An example:

public class DashboardViewModel extends NavHostViewModel {

    public DashboardViewModel(String title) {
        super(title);
    }

    static class Factory implements ViewModelProvider.Factory {
        private String title;

        Factory(String title) {
            this.title = title;
        }

        @SuppressWarnings("unchecked")
        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            return (T) new DashboardViewModel(title);
        }
    }
}

Then instantiating the ViewModel inside its fragment:

public class DashboardView extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        DashboardBinding binding = DashboardBinding.inflate(inflater, container, false);
        DashboardViewModel viewModel =
                ViewModelProviders.of(this, new DashboardViewModel.Factory("Dashboard"))
                        .get(DashboardViewModel.class);
        binding.setVm(viewModel);
        binding.setLifecycleOwner(getViewLifecycleOwner());
        return binding.getRoot();
    }
}

All that doesn't produce what I'm expecting -- the text of the TextView in the toolbar doesn't change, and I'm seeing only the value initially passed when instantiating the NavHostViewModel. No errors are being thrown.

I've had a look and tried this which happens to be the only related question I've found so far that comes closest to my particular problem, but no progress.

Please advise.

Zero
  • 717
  • 6
  • 21
  • Have you solved this? I am stuck in a similar situation. If you could help with any solution,it would be better – Shijilal Sep 01 '20 at 04:37
  • 1
    What I did was drop the Navigation Architecture Component (one activity and many fragments) entirely and just revert to using a BaseActivity (with many activities). I already had the BaseActivity setup working and was only checking out the NAC on a different Git branch. The NAC proved unsatisfactory so I just deleted that branch and moved on. – Zero Sep 01 '20 at 14:05
  • Thanks for the response.I am still trying to find a way out of this in here : https://github.com/Shijilal/Toolbar-MVVM-DataBinding – Shijilal Sep 01 '20 at 14:23

1 Answers1

0
  1. make a child-layout to accept its VM type and the parent-layout to accept common VM type
  2. in the child-layout cast its VM to common one.

Here is a piece of my xml

<data>

    <variable
        name="viewModel"
        type="com.mincom.tools.jemoni.ui.main.fragments.jobs.JobsViewModel" />
</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.main.fragments.jobs.JobsFragment">

    <include
        android:id="@+id/toolbar"
        layout="@layout/main_common_toolbar"
        app:viewModel="@{(com.mincom.tools.jemoni.ui.main.BaseToolbarViewModel) viewModel}" />
</LinearLayout>/>