【问题标题】:Roboguice injection into adapterRoboguice 注入适配器
【发布时间】:2012-09-07 10:46:07
【问题描述】:

我有一个扩展 ArrayAdapter<T> 的适配器,并希望将其注入 LayoutInflater。代码如下,但inflater总是null

public abstract class MyAdapter<T> extends ArrayAdapter<T> {

    @Inject
    protected LayoutInflater inflater;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // inflater here is null
    }
}

【问题讨论】:

    标签: android code-injection roboguice


    【解决方案1】:

    在任何类中注入依赖项

     RoboGuice.getInjector(context).injectMembers(this);
    

    在构造函数中使用,只需要上下文, 对我来说很棒的作品

    【讨论】:

      【解决方案2】:

      您可能使用new 创建了MyAdapter 实例,而不是注入它。

      在这种情况下,我不建议注入LayoutInflater,除非您想使用此类的不同实现,例如模拟LayoutInflater 进行测试。

      在构造函数中获取实例:

      inflater = LayoutInflater.from(context);
      

      这样会更有效率。我看不到注入 LayoutInflater 的任何好处。
      依赖注入是可以的,但是没必要的时候不要用,而且速度慢。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多