Home > Blockchain >  Kotlin: Activity doesn't support ViewModelStoreOwner
Kotlin: Activity doesn't support ViewModelStoreOwner

Time:01-11

I used Activity(), not AppcompatActivity() to make transparent background.

class CommentActivity : Activity() {

And when I tried to create ViewModel, I can't use this as ViewModelStoreOwner.

How can I solve this problem?

enter image description here

CodePudding user response:

You have to at least extend ComponentActivity, native Activity doesn't contain any support for androidx components.

CodePudding user response:

Try implementing the ViewModelStoreOwner interface:

 class MainActivity : Activity(), ViewModelStoreOwner{
    companion object{
        var VIEWMODEL_STORE:ViewModelStore? = null
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val testViewModel:TestViewModel = ViewModelProvider(this).get(TestViewModel::class.java)

        val textView = findViewById<TextView>(R.id.test_text)
        textView.text = testViewModel.testMessage()
        Log.i("MainActivity",testViewModel.testMessage())
    }

    override fun getViewModelStore(): ViewModelStore {
        if(VIEWMODEL_STORE == null){
            VIEWMODEL_STORE = ViewModelStore()
        }
        return VIEWMODEL_STORE!!
    }

}

The viewModel class stays without changes:

class TestViewModel:ViewModel() {

    fun testMessage():String = "From TestViewModel ${hashCode()}"
}
  • Related