CustomView dependency injection with dagger 2 (within activity scope)

前端 未结 2 1387
广开言路
广开言路 2021-02-02 13:04

My question is similar to this.

So for instance, I have a LiveData implementation:

public class CustomLiveData extends LiveData

        
2条回答
  •  日久生厌
    2021-02-02 13:41

    tl;dr Don't inject model layer dependencies inside custom View objects

    Subclasses of View are not good targets for Dagger 2 injection. View objects are meant to be drawn and not must else, hence the name "view". The constructors for View should make this clear; they are designed for inflating View objects from attributes specified in XML. In other words, a View object should be able to be specified in a layout.xml file, inflated at the appropriate point in the lifecycle, and then obtained using findViewById(int id), Butterknife or data binding. In this way, the best custom View objects take no dependencies.

    If you want to link a View and some data from the model layer, the standard pattern is to write an Adapter like those for RecyclerView and ListView. If this is not possible, using a setter (e.g., setData()) is preferable to passing dependencies from the model layer in the constructor or requesting injection from within one of the lifecycle methods of the View.

    If instead you inject your LiveData object inside an Activity or Fragment using the AndroidInjector class the correct Context will be provided without you having to do anything. This explains your comment "I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view."

    Once you have injected the LiveData object into the Activity, use one of the above methods (an adapter or a setter) to associate the data with your custom View. See the Google Android Architecture example here where elements from the model layer are injected using Dagger 2 and then associated with a ListView using findViewById and setAdapter()

    Link to the Dagger 2 issue where injection of View objects is discussed:

    https://github.com/google/dagger/issues/720

提交回复
热议问题