【问题标题】:ViewModel databinding inheritance not workingViewModel 数据绑定继承不起作用
【发布时间】:2019-04-05 13:53:46
【问题描述】:

我有一个想要迁移到 MVVM + Jetpack 的 MVP 应用程序。使用导航架构组件 (NAC),我现在的设置是我有一个 NavHostActivity 及其布局文件,activity_nav_host.xml 包含一个 DrawerLayout、一个 Toolbar 和一个 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>

在使用 NAC 时,建议使用一个活动和多个片段。在上面的文件中,@+id/fragment_nav_host 是这些片段的容器,对于每个屏幕,我打算相应地更改工具栏标题。以下是随附工具栏 (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>

以及 NavHostActivity 的 ViewModel:

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);
        }
    }
}

最后,这是 NavHostActivity 本身:

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);
    }
}

现在,由于每个片段屏幕都有自己的工具栏标题,并且标题将来自该特定片段的 ViewModel,我让 ViewModel 扩展 NavHostViewModel 然后使用 super() 调用设置标题父构造函数。一个例子:

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);
        }
    }
}

然后在其片段中实例化 ViewModel:

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();
    }
}

所有这些都没有产生我所期望的——工具栏中的 TextView 的文本没有改变,而且我只看到在实例化 NavHostViewModel 时最初传递的值。没有抛出任何错误。

我已经查看并尝试了this,这恰好是迄今为止我发现的唯一一个与我的特定问题最接近的相关问题,但没有进展。

请指教。

【问题讨论】:

  • 你解决了吗?我陷入了类似的境地。如果您能提供任何解决方案,那就更好了
  • 我所做的是完全放弃导航架构组件(一个活动和许多片段),而只是恢复使用 BaseActivity(具有许多活动)。我已经有 BaseActivity 设置工作,只是在不同的 Git 分支上检查 NAC。 NAC 证明不令人满意,所以我删除了那个分支并继续前进。
  • 感谢您的回复。我仍在尝试在这里找到解决方法:github.com/Shijilal/Toolbar-MVVM-DataBinding

标签: android android-fragments android-databinding android-mvvm


【解决方案1】:
  1. 创建子布局以接受其 VM 类型,并创建父布局以接受通用 VM 类型
  2. 在子布局中将其虚拟机转换为普通虚拟机。

这是我的一段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>/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2017-08-12
    • 1970-01-01
    • 2010-12-07
    • 2022-01-14
    • 2018-05-24
    相关资源
    最近更新 更多