MVP

MVP.png

案例分享:https://blog.csdn.net/qq_34023088/article/details/81027384

IP:

abstract class IPresenter(v: T) {
    open var mView: SoftReference = SoftReference(v)
    open fun onCreate(intent: Intent?) {
        mView.get()?.initView()
    }
}

IV:

interface IView {
    val mPresenter: IPresenter
    fun initView()
    fun showProgressDialog(){}
    fun dismissProgressDialog(){}
    fun showToast(text:String,context: Context,time:Int=Toast.LENGTH_SHORT){
        Toast.makeText(context,text,time).show()
    }
}

BaseActivity

abstract class BaseActivity: Activity(), IView {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        addPresenters()
        mPresenter.onCreate(intent) }
    }
    abstract fun getLayoutId():Int
    override fun showProgressDialog() {
        super.showProgressDialog()
    }
    override fun dismissProgressDialog() {
        super.dismissProgressDialog()
    }
}

XXXModel

object UserModel {
    fun addUser(name : String ,listener : (Boolean) -> Unit){
          //做一些没什么耗时或者具体的任务,比如添加用户
          Thread.sleep(3000)
           if(name=="礼拜"){
                  listener(true)
           }else{
                  listener(false)
           }
    }
}

XXXConstact

interface UserContract {
    interface IUserView : IView {
        fun showAddUserResult(boolean: Boolean)
    }
    interface IUserPresenter{
        fun addUser(name:String)
    }
}

XXXPresenter

class UserPresenter(view: UserContract.IUserView):UserContract.IUserPresenter, IPresenter(view) {
    override fun addUser(name: String) {
        //弹出对话框
        mView.get()?.showProgressDialog()
        //做一些校验
        if (!TextUtils.isEmpty(name)){
            UserModel.addUser(name) {
                //关闭对话框并显示结果
                mView.get()?.dismissProgressDialog()
                mView.get()?.showAddUserResult(it)
            }
        }
    }
}

XXXActivity

class MainActivity: BaseActivity(),UserContract.IUserView {
    override val mPresenter: UserPresenter= UserPresenter(this)
    override fun getLayoutId(): Int = R.layout.activity_main
    override fun initView() {
        tvUser.setOnClickListener {
            mPresenter.addUser("卡丽熙")
        }
    }
    override fun showAddUserResult(boolean: Boolean) {
        if (boolean){
            tvUser.text = "添加用户成功"
        }else{
            tvUser.text = "添加用户失败"
        }
    }
}

你可能感兴趣的:(MVP)