ViewModelProvider - .与Fragment不兼容的类型

问题描述 投票:0回答:1

我的Android程序曾经工作正常,我使用Android studio来获取底部导航查看活动。有用。当我在实际的手机设备中运行后,它不再工作了,它抱怨如下:

不兼容的类型:HomeFragment 无法转换为 ViewModelProviderImpl new ViewModelProvider(this).get(HomeViewModel.class);

HomeViewModel.java 是由 Andorid studio 生成的,在我选择创建底部导航视图 Activity 后。

package com.abc.myapplication.ui.home;

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

public class HomeViewModel extends ViewModel {

    private final MutableLiveData<String> mText;

    public HomeViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is home fragment");
    }

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

我的HomeFragment.java如下所示,也是由Android Studio生成的。

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        // new code
        HomeViewModel= new ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textHome;
        homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }

有人请建议并尽可能给我示例代码吗?

java android
1个回答
0
投票

我在使用 Java 而不是 Kotlin 时遇到了类似的问题,并且在

compiledSDK
(应用程序)中将
build.gradle
版本设置为 34。将
compiledSDK
版本设置为 33 实际上可以解决这个问题。您将不得不降级
build.gradle
中的一些库。

© www.soinside.com 2019 - 2024. All rights reserved.