git-xuhao / KotlinMvp

:fire: 基于Kotlin+MVP+Retrofit+RxJava+Glide 等架构实现短视频类小项目,简约风格及详细注释,欢迎 star or fork!
https://xuhaoblog.com/KotlinMvp
Apache License 2.0
3.69k stars 917 forks source link

kotlin可以避免每个子Activity都调attachView吗 #31

Closed mackwu828 closed 6 years ago

mackwu828 commented 6 years ago

我之前在把mvp从java转到kotlin时,碰到基类里调用attachView(this)这里编译不过,看了你的源码,你是在每个子view里都调用一遍attachView CategoryDetailActivity: init { mPresenter.attachView(this) }

如果基类调用,kotlin会出现 Type mismatch,在基类中有解决方法吗,不是用Java解决 abstract class MvpActivity<P : IPresenter<*>> : RxAppCompatActivity(), IView {

protected var mPresenter: P? = null

/**
 * 初始化presenter
 */
abstract fun initPresenter(): P

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (null == mPresenter) {
        mPresenter = initPresenter()
    }
    // 绑定View
    if (null != mPresenter) {
        // Type mismatch.
        mPresenter!!.attachView(this)
    }
git-xuhao commented 6 years ago

@wmjwmj828 可以的,你可以试下,下面是伪代码,不过也可以用 dagger2 实现

abstract class BaseActivity <V:BaseView,T :BasePresenter<V>>: AppCompatActivity(),BaseView {
 open var mPresenter:T?=null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (null == mPresenter) {
        mPresenter = initPresenter()
    }
   mPresenter!!.attachView(this as V)
}
mackwu828 commented 6 years ago

@git-xuhao 这样子类还要传View,好麻烦,哎如果as BaseView还编译不过 mPresenter!!.attachView(this as BaseView)

mackwu828 commented 6 years ago

用dagger都不用方法注入view了,还是先不用dagger的方法实现,更容易理解

wangyuan0217 commented 6 years ago

楼主解决了没,我项目也遇到这个问题,改成kotlin了,结果泛型这边和java有点不同,编译不过,暂时BaseActivity的基类都还是java,不知道如何转kotlin(BaseActivity明明已经实现了BaseView,mPresenter却不能attach(this))

zhupengxiang commented 5 years ago

同求解决办法 @wmjwmj828 @wangyuan0217 我现在基类也是java

wangyuan0217 commented 5 years ago

不知道欸

git-xuhao commented 5 years ago

@zhupengxiang @wangyuan0217 上面不是提供的有方案吗?有试过么?