kotlin 主活动中的ViewModelProvider [重复]

hwamh0ep  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(122)

此问题已在此处有答案

Navigation Component: How to set drawer with toolbar in each fragment(2个答案)
5天前关闭。
我尝试了一些东西,但无法修复此错误,这是我的主活动代码

class MainActivity : AppCompatActivity() {
    private lateinit var binding : ActivityMainBinding
    private lateinit var navController: NavController
    lateinit var viewModel : NewsViewModel
    val db : ArticleDatabase? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val newsRepository =  NewsRepository(ArticleDatabase(this))
        val viewModelProviderFactory = NewsViewModelProviderFactory(newsRepository)
        viewModel = ViewModelProvider(this,viewModelProviderFactory)[NewsViewModel::class.java]
        navController = Navigation.findNavController(this, R.id.newsNavHostFragment)
        setupWithNavController(binding.bottomNavigationView,navController)


    }
}

这是片段代码

class BrakingNewsFragment : Fragment() {
    lateinit var viewModel : NewsViewModel
    lateinit var newsAdapter : NewsAdapter
    private lateinit var binding : FragmentBrakingNewsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentBrakingNewsBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = (activity as MainActivity).viewModel
        setUpRecyclerView()

        viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response ->
            when(response){
                is Resource.Succes -> {
                    response.data?.let {
                        newsAdapter.differ.submitList(it.articles)
                    }
                }
                is Resource.Loading -> {
                    println("abcabc")
                }
            }
        })
    }
    private fun setUpRecyclerView(){
        newsAdapter = NewsAdapter()
        binding.breakingNewsRecyclerView.apply {
            adapter = newsAdapter
            layoutManager = LinearLayoutManager(activity)
        }
    }

}

这是一个很好的例子。

class NewsViewModelProviderFactory(private val newsRepository: NewsRepository) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return NewsViewModel(newsRepository) as T
    }
}

logcat错误在这里
原因:android.view.InflateException:二进制XML文件行#19在com.example. newsletter kotlin:layout/activity_main中:二进制XML文件行#19在com.example. newsletter kotlin:layout/activity_main中:膨胀类片段时出错,原因:android.view.InflateException:二进制XML文件行#19在com.example. newsletter kotlin:layout/activity_main中:膨胀类片段时出错,原因:Kotlin. UninitializedPropertyException:lateinit属性viewModel尚未初始化
如何才能修复

hk8txs48

hk8txs481#

你不能这样示例化视图模型:

viewModel = (activity as MainActivity).viewModel

为什么不使用

val viewModel : NewsViewModel by viewModels()

或者因为这可能是一个带有Activity的sharedViewModel:

val viewModel: NewsViewModel by activityViewModels()

在执行此操作之前,您需要viewModels的Kotlin扩展依赖项。

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.6.1"
}

相关问题