2012-09-14 76 views
4

我有一个适配器,它扩展了ArrayAdapter<T>并且想要注入到它们中LayoutInflater。下面的代码提交,但吹气总是nullRoboguice注入适配器

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 
    } 
} 

回答

5

也许你已经创建MyAdapter实例与new,而不是将其注入的。

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

获取实例中的构造函数:

inflater = LayoutInflater.from(context); 

这将是更有效的。我看不到注入LayoutInflater有任何好处。
依赖注入是好的,但不要在没有必要和缓慢时使用它。

+0

是我创造我的适配器实例与'new'因为我应该把参数传递到构造函数。我如何将它注入活动?我如何选择需要的构造函数并将参数传递给它? –

+0

将args传入构造函数:http://stackoverflow.com/questions/9237996/pass-parameter-to-constructor-with-guice 或'injectMembers':http://stackoverflow.com/questions/5116383/guice- injectmembers-method 这两种解决方案在你的情况是丑陋的:) – pawelzieba

5

注入依赖任何类

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

在构造函数中使用,只需要语境, 伟大的作品对我来说