kotlin Dagger2 适配器中的依赖注入

Dependency Injection in Adapter in kotlin Dagger2

预期结果

我想做的是将我的 AccountType class 注入到 ExpandableAdpter 并在点击子视图时检查用户类型?

如何在Adapter中实现dagger?

Dagger 与 Fragment 和 Activity 配合得很好。由于无法将适配器初始化为匕首,因此只能在适配器中获取 null

dagger 界面示例

//Di interface 
interface ActivityComponent : BaseComponent {
// adapter
fun inject(expDragSwipeAdapter: ExpandableDraggableSwipeableAdapter)

}

组和子视图的适配器onCreate

@Inject lateinit var accountType: Accounts
private lateinit var activityComponent: ActivityComponent

override fun onCreateGroupViewHolder(parent: ViewGroup, viewType: Int): MyGroupViewHolder {
    activityComponent.inject(this)
    val inflater = LayoutInflater.from(parent.context)
    val v: View
    if (isDragRequire) {
        v = inflater.inflate(R.layout.row_edit_watchlist, parent, false)
    } else {
        v = inflater.inflate(R.layout.row_watchlist, parent, false)
    }
    return MyGroupViewHolder(v, isDragRequire, mContext)
}

override fun onCreateChildViewHolder(parent: ViewGroup, viewType: Int): MyChildViewHolder {
    activityComponent.inject(this)
    val inflater = LayoutInflater.from(parent.context)
    val v = inflater.inflate(R.layout.row_child_watchlist, parent, false)
    return MyChildViewHolder(v, false)
}

我遇到了这一行的错误activityComponent.inject(this)

Onclick检查AccountType并实现业务逻辑

无需请求从适配器内的 Dagger 2 组件注入 RecyclerView 或 ListView。

对于片段和活动,我们别无选择,只能明确请求从组件注入,因为这些对象是由 Android OS 实例化的,而我们 "control"构造函数。

对于其他一切,包括适配器,您应该更喜欢构造函数注入,然后手动设置参数。

惯用的东西看起来像下面这样。在你的片段中:

class MyFragment : Fragment {

    @Inject
    lateinit var accountsAdapter: accountsAdapter

    @Inject
    lateinit var accountsRepository: AccountsRepository

    //load accounts in onStart or wherever you decide to load
    //when loading finished, execute the following method in a callback

    fun onAccountsLoaded(accounts: Accounts) {
        adapter.setAccounts(accounts)
    }
}

例如,您的适配器可以执行以下操作:

class Adapter @Inject constructor() : BaseAdapter {

    fun setAccounts(accounts: Accounts) {
        this.accounts = accounts
        notifyDataSetChanged()
    } 
}

你可以看官方Google Android ListView with Dagger 2 的架构示例。link 是here