使用 viewLifecycleOwner 时未解决的引用错误
Unresolved reference error when using viewLifecycleOwner
我在 android 项目中使用 Observer 和 viewLifecycleOwner 时遇到错误。它抛出 "Unresolved reference: viewLifecycleOwner" 错误,我不知道为什么。我确认我有进口商品
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
以及依赖关系:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
我已尝试使缓存无效/重新启动... GitHub 中找到的解决方案。但错误仍然存在。感谢任何能帮助我的人。
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: DrinkViewModel
// Contains all the views
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use Data Binding to get reference to the views
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.drinkButton.setOnClickListener {
onDrinkClicked()
}
viewModel.revenue.observe(viewLifecycleOwner, Observer { newRevenue ->
binding.revenueText.text = newRevenue.toString()
})
viewModel.drinksSold.observe(viewLifecycleOwner, Observer { newAmount ->
binding.amountSoldText.text = newAmount.toString()
})
binding.drinkButton.setImageResource(viewModel.currentDrink.value!!.imageId)
}
}
getViewLifecycleOwner() is method to represent fragment's lifeCycle. You can't call it from activiy scope. You can just use this
or if you are familiar with coroutines, you can use lifeCycleScope .
我在 android 项目中使用 Observer 和 viewLifecycleOwner 时遇到错误。它抛出 "Unresolved reference: viewLifecycleOwner" 错误,我不知道为什么。我确认我有进口商品
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
以及依赖关系:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
我已尝试使缓存无效/重新启动... GitHub 中找到的解决方案。但错误仍然存在。感谢任何能帮助我的人。
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: DrinkViewModel
// Contains all the views
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use Data Binding to get reference to the views
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.drinkButton.setOnClickListener {
onDrinkClicked()
}
viewModel.revenue.observe(viewLifecycleOwner, Observer { newRevenue ->
binding.revenueText.text = newRevenue.toString()
})
viewModel.drinksSold.observe(viewLifecycleOwner, Observer { newAmount ->
binding.amountSoldText.text = newAmount.toString()
})
binding.drinkButton.setImageResource(viewModel.currentDrink.value!!.imageId)
}
}
getViewLifecycleOwner() is method to represent fragment's lifeCycle. You can't call it from activiy scope. You can just use this
or if you are familiar with coroutines, you can use lifeCycleScope .