Search code examples
androidcode-injectionroboguice

Roboguice injection into adapter


I have an adapter which extends ArrayAdapter<T> and want to inject into them LayoutInflater. Code presented below, but inflater is always 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
    }
}

Solution

  • Probably you've created MyAdapter instance with new instead of injecting it.

    In this case I would not recommend to inject LayoutInflater, unless you want to use different implementations of this class, example mock of LayoutInflater for testing.

    Obtain the instance in constructor:

    inflater = LayoutInflater.from(context);
    

    It would be more efficient. I can't see any benefit from injecting LayoutInflater.
    Dependency injection is ok, but don't use it when it's not necessary and slow.