android - 安卓 - 使用dagger将ViewModelProvider.Factory注入到不同的Activity

我有以下Activity,当请求成功,API返回有效的LoggedInUser时,我想导航到不同的Activity,并且仍然可以访问LoggedInUser。

以下是loginActivity:


class LoginActivity : AppCompatActivity() {



 val vmFactory = MainViewModelFactory()


 lateinit var viewModel: MainViewModel



 override fun onCreate(savedInstanceState: Bundle?) {


 super.onCreate(savedInstanceState)


 setContentView(R.layout.activity_login)


 val button: Button = findViewById(R.id.button)


 button.setOnClickListener { onButtonClick() }


 val label: TextView = findViewById(R.id.counter)



 viewModel = ViewModelProvider(this, vmFactory).get(MainViewModel::class.java)


 println("stack: ${viewModel.hashCode()}")



 viewModel.userLogin.observe(this, Observer{ user ->


 print("Debug: ${user}")


 if(user != null){


 label.text = user.user.name


 redirectToNextActivity()



 }



 })



 }



 fun onButtonClick(){


 var username: EditText = findViewById(R.id.username)


 var password: EditText = findViewById(R.id.password)


 println(username.text.toString())


 println(password.text.toString())


 viewModel.setUser(username.text.toString(), password.text.toString())


 }



 fun redirectToNextActivity(){


 println("Login done!")


 val intent = Intent(this, SampleActivity::class.java)


 startActivity(intent)


 }



}



以下是ViewModel和ViewModelFactory:

MainViewModel:


class MainViewModel : ViewModel(){



 var _request = MutableLiveData<LoginRequest>()



 val userLogin: LiveData<LoggedInUser> = Transformations


 .switchMap(_request){req ->


 MainRepository.authenticatePlease(req.username, req.password)


 }



 fun setUser(username: String, password: String){


 val update = LoginRequest(username, password)


 if(_request.value == update){


 return


 }


 _request.value = update


 }



}



这是工厂:


class MainViewModelFactory: ViewModelProvider.Factory {


 override fun <T : ViewModel?> create(modelClass: Class<T>): T {


 return MainViewModel() as T


 }


}



当我尝试在新的Activity中获取工厂时,我得到以下错误:

SampleActivity has no zero argument constructor

然后,我尝试在vmFactory中传递loginActivity,如下所示:

val intent = Intent(this, SampleActivity(vmFactory)::class.java)

我还是得到同样的错误。

SampleActivity如下所示:


class SampleActivity@Inject constructor(private val factory: ViewModelProvider.Factory) : AppCompatActivity() {



 lateinit var viewModel: MainViewModel



 override fun onCreate(savedInstanceState: Bundle?) {


 super.onCreate(savedInstanceState)


 setContentView(R.layout.activity_sample)


 viewModel = ViewModelProvider(this, factory).get(MainViewModel::class.java)



 }


}



有什么帮助!

时间: 作者:

  • 不应将参数添加到Activity的构造函数

由于Android操作系统控制Activity,BroadcastReceiver,Service,ContentProvider和Application类的实例化,因此开发人员无权访问Android组件的构造函数。

请查看更多信息:https://levelup.gitconnected.com/understanding-dependency-injection-in-android-af1bb2b7984e

  • 如果希望访问示例LoggedInUser中的Activity,可以在Intent中将对象作为附加参数发送

    
    fun redirectToNextActivity(loggedInUser: LoggedInUser) {
    
    
    println("Login done!")
    
    
    val intent = Intent(this, SampleActivity::class.java)
    
    
    intent.putExtra("extra", loggedInUser)
    
    
    startActivity(intent)
    
    
    }
    
    
    
    

    或者,可以将MainViewModel类标记为Singleton,以便接收两个activity中的相同实例

作者:
...