如何使用dagger2将活动注入适配器

时间:2017-07-31 15:13:52

标签: android dagger-2

Android Studio 3.0 Canary 8

我正在尝试将我的MainActivity注入我的适配器。但是,我的解决方案工作正常,但我认为它的代码味道并不是正确的方法。

我的适配器代码段看起来像这样,但我不喜欢这是因为我必须将Activity强制转换为MainActivity

public class RecipeAdapter extends RecyclerView.Adapter<RecipeListViewHolder> {
    private List<Recipe> recipeList = Collections.emptyList();
    private Map<Integer, RecipeListViewHolderFactory> viewHolderFactories;
    private MainActivity mainActivity;

    public RecipeAdapter(Activity activity, Map<Integer, RecipeListViewHolderFactory> viewHolderFactories) {
        this.recipeList = new ArrayList<>();
        this.viewHolderFactories = viewHolderFactories;
        this.mainActivity = (MainActivity)activity;
    }

    @Override
    public RecipeListViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        /* Inject the viewholder */
        final RecipeListViewHolder recipeListViewHolder = viewHolderFactories.get(Constants.RECIPE_LIST).createViewHolder(viewGroup);

        recipeListViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* Using the MainActivity to call a callback listener */
                mainActivity.onRecipeItemClick(getRecipe(recipeListViewHolder.getAdapterPosition()));
            }
        });

        return recipeListViewHolder;
    }
}

在我的模块中,我传递模块构造函数中的Activity并将其传递给适配器。

@Module
public class RecipeListModule {
    private Activity activity;

    public RecipeListModule() {}

    public RecipeListModule(Activity activity) {
        this.activity = activity;
    }

    @RecipeListScope
    @Provides
    RecipeAdapter providesRecipeAdapter(Map<Integer, RecipeListViewHolderFactory> viewHolderFactories) {
        return new RecipeAdapter(activity, viewHolderFactories);
    }
}

在My Application类中,我创建了组件,我正在为适配器使用SubComponent。在这里,我必须通过我不确定是一个好主意的活动。

@Override
public void onCreate() {
    super.onCreate();

    applicationComponent = createApplicationComponent();
    recipeListComponent = createRecipeListComponent();
}

public BusbyBakingComponent createApplicationComponent() {
    return DaggerBusbyBakingComponent.builder()
            .networkModule(new NetworkModule())
            .androidModule(new AndroidModule(BusbyBakingApplication.this))
            .exoPlayerModule(new ExoPlayerModule())
            .build();
}

public RecipeListComponent createRecipeListComponent(Activity activity) {
    return recipeListComponent = applicationComponent.add(new RecipeListModule(activity));
}

My Fragment我这样注射:

@Inject RecipeAdapter recipeAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ((BusbyBakingApplication)getActivity().getApplication())
                .createRecipeListComponent(getActivity())
                .inject(this);
    }

即使上面的设计有效,我认为这是代码味道,因为我必须将Activity转换为MainActivity。我之所以使用Activity,是因为我想让这个模块更通用。

只是想知道是否有更好的方式

===============使用界面更新

接口

public interface RecipeItemClickListener {
    void onRecipeItemClick(Recipe recipe);
}

实施

public class RecipeItemClickListenerImp implements RecipeItemClickListener {
    @Override
    public void onRecipeItemClick(Recipe recipe, Context context) {
        final Intent intent = Henson.with(context)
                .gotoRecipeDetailActivity()
                .recipe(recipe)
                .build();

        context.startActivity(intent);
    }
}

在我的模块中,我有以下提供者

@Module
public class RecipeListModule {
    @RecipeListScope
    @Provides
    RecipeItemClickListener providesRecipeItemClickListenerImp() {
        return new RecipeItemClickListenerImp();
    }

    @RecipeListScope
    @Provides
    RecipeAdapter providesRecipeAdapter(RecipeItemClickListener recipeItemClickListener, Map<Integer, RecipeListViewHolderFactory> viewHolderFactories) {
        return new RecipeAdapter(recipeItemClickListener, viewHolderFactories);
    }
}

然后我通过RecipeAdapter中的构造函数注入使用它

public class RecipeAdapter extends RecyclerView.Adapter<RecipeListViewHolder> {
    private List<Recipe> recipeList = Collections.emptyList();
    private Map<Integer, RecipeListViewHolderFactory> viewHolderFactories;
    private RecipeItemClickListener recipeItemClickListener;

    @Inject /* IS THIS NESSESSARY - AS IT WORKS WITH AND WITHOUT THE @Inject annotation */
    public RecipeAdapter(RecipeItemClickListener recipeItemClickListener, Map<Integer, RecipeListViewHolderFactory> viewHolderFactories) {
        this.recipeList = new ArrayList<>();
        this.viewHolderFactories = viewHolderFactories;
        this.recipeItemClickListener = recipeItemClickListener;
    }

    @Override
    public RecipeListViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
        /* Inject the viewholder */
        final RecipeListViewHolder recipeListViewHolder = viewHolderFactories.get(Constants.RECIPE_LIST).createViewHolder(viewGroup);

        recipeListViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recipeItemClickListener.onRecipeItemClick(getRecipe(recipeListViewHolder.getAdapterPosition()), viewGroup.getContext());
            }
        });

        return recipeListViewHolder;
    }
}

只有一个问题,是RecipeAdapter中构造函数的@Inject注释需求。因为它可以使用或不使用@Inject。

3 个答案:

答案 0 :(得分:11)

不要将活动传递给适配器 - 这是一种非常糟糕的做法。

仅注入您关注的字段。

在您的示例中:将接口传递到适配器以跟踪项目单击。

答案 1 :(得分:7)

如果您需要MainActivity,那么您也应该提供它。 Activity为您的模块声明MainActivity

@Module
public class RecipeListModule {
  private MainActivity activity;

  public RecipeListModule(MainActivity activity) {
    this.activity = activity;
  }
}

您的适配器应该只是请求它( Android Framework类型的构造函数注入!)

@RecipeListScope
class RecipeAdapter {

  @Inject
  RecipeAdapter(MainActivity activity,
          Map<Integer, RecipeListViewHolderFactory> viewHolderFactories) {
    // ...
  }

}

如果您希望模块使用Activity而不是MainActivity,那么您需要声明已经提到的接口。然后,适配器会将接口声明为其依赖项。

但在某些模块中,您仍然必须将该接口绑定到MainActivity,并且一个模块需要知道如何提供依赖项。

// in some abstract module
@Binds MyAdapterInterface(MainActivity activity) // bind the activity to the interface

解决问题的更新部分

  

只有一个问题,是RecipeAdapter中构造函数的@Inject注释需求。因为它适用于或不适用@Inject

它没有它,因为你还没有使用构造函数注入。您仍然在providesRecipeAdapter()中自行调用构造函数 。作为一般经验法则 - 如果您想正确使用Dagger - 请不要自己致电new。如果你想使用new问问自己是否可以使用构造函数注入。

您显示的相同模块可以编写如下,使用@Binds将实现绑定到接口,并实际使用构造函数注入来创建适配器(这就是为什么我们没有为它编写任何方法!维护的代码更少,错误更少,类更易读)

如你所见,我不需要自己使用new - Dagger会为我创建物品。

public abstract class RecipeListModule {
  @RecipeListScope
  @Binds
  RecipeItemClickListener providesRecipeClickListener(RecipeItemClickListenerImp listener);
}

答案 2 :(得分:2)

就个人而言,我会做以下技巧

  # Program to display prime number till n nubers

def prime(number):
    for num in range(2,number):
        status = True
        for i in range(2,num):
            if num % i == 0:
                status = False
        if status:
            print(num)


prime(101)

print "Program Ends here"