Kotlin-适配器上的“ android.app.Application无法转换为android.app.Activity”

时间:2018-11-27 12:59:48

标签: android android-activity kotlin adapter

当我选择一个bottomNavigationView的项目时,我试图调用一个意图:

 R.id.nova_foto_barra_cartao -> {
      val intent = CameraView.buildIntent(context.applicationContext, Constants.ULCERS)
      (context as Activity).startActivityForResult(intent, 0)
 }

代码写在适配器内部:

class CartaoTipologiaAdapter(private val cartoesTipologia: List<CartaoTipologia>, private val context: Context) : Adapter<CartaoTipologiaAdapter.ViewHolder>()

3 个答案:

答案 0 :(得分:1)

You're most likely passing an application context into the adapter, which you then cast to an Activity. So having a crash here is the expected behavior.

It's safer to provide a custom callback from your adapter to the place where it is used. This lets you create the adapter without hard wiring its behavior to the activity. Then your callback implementation can take care of the action to perform.

答案 1 :(得分:0)

在创建CartaoTipologiaAdapter实例的代码中,请确保将Activity传递为context,而不是context.applicationContext。如果您在活动中创建CartaoTipologiaAdapter的实例,请以context的形式传递活动:

val adapter = CartaoTipologiaAdapter(yourList, this@YourActivity)

答案 2 :(得分:0)

您必须通过[您当前的活动]。此