如何使用Dagger2 for android将视图注入到演示者中?

问题描述 投票:0回答:1

我想将injectview (Activity object)转换为Presenter。现在,我正在使用Presenter类的setter手动设置视图。如何使用Dagger实现此目的?您能给我示范一下如何做的示例代码吗?

这是到目前为止主要活动创建演示者的方式

public class MainActivity extends AppCompatActivity implements CountPresenter.View, ToastPresenter.View {

    @Inject
    CountPresenter countPresenter;
    @Inject
    ToastPresenter toastPresenter;
    TextView countText;
    Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        countText = findViewById(R.id.text_count);

        DaggerToastPresenterComponent.create().inject(this);
        DaggerCountPresenterComponent.create().inject(this);
        countPresenter.setView(this);
        toastPresenter.setView(this) ;

        findViewById(R.id.button_count).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countPresenter.incrementCount();
            }
        });

        findViewById(R.id.button_toast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toastPresenter.handleToastButtonClick();
            }
        });
    }
}

**演讲者课程代码:**

public class CountPresenter {
    private Counter counter ;


    public void setView(View view) {
        this.view = view;
    }

    private View view ;

    @Inject
    public CountPresenter() {
        counter =  Counter.getInstance() ;
    }

    public void incrementCount(){
        counter.setCount(counter.getCount()+1);
        view.setCounterText(counter.toString());
    }

    public interface View {
        void setCounterText(String val) ;
    }
}

完整代码在这里:

https://github.com/nateshmbhat/FresherAssignment2020/tree/nateshmbhat/Apps/CounterApp_MVP_Dagger/app/src/main/java/com/techy/nateshmbhat/contacto

android dependency-injection dependencies dagger
1个回答
0
投票

我要写下步骤

首先,您需要添加module

@Module
class CountPresenterModule {
    @Provides
    @Singleton
    fun providCountPresenter(): CountPresenter.View {
        return CountPresenter()
    }
}

类似地为ToastPresenter添加模块类

之后,在AppComponent类中添加新添加的模块类的引用

@Singleton
@Component(modules = [AppModule::class, .....,ToastPresenterModule::class, CountPresenterModule::class]){
    fun inject(mainActivity: MainActivity)
}

并且被匕首/注入的魔咒逗乐了。

© www.soinside.com 2019 - 2024. All rights reserved.