教你从0到1搭建一个完整的电商app---(MVP封装)

xiaoxiao2025-07-09  14

上一篇我们已经创建好了基本的项目,一个App主工程,BaseLibrary和Provider两个基本Module,这三个部分我们以后可以在所有的项目中直接使用,这也是模块化管理的好处。 这篇博客主要介绍如何封装一个最基本的MVP框架,我们都知道MVP模式在Android开发中被大量使用,这样能够将业务逻辑和视图显示区分开,降低耦合性,提高代码可读性。接下来就让我们看具体的代码吧 。

interface BaseView { fun showLoading() fun hideLoading() fun onError(text: String) } open class BasePresenter<T: BaseView> { lateinit var mView: T } open class BaseActivity:AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } } open class BaseMvpActivity<T : BasePresenter<*>> : BaseActivity(), BaseView { lateinit var mPresenter: T override fun hideLoading() { } override fun onError(text: String) { } override fun showLoading() { } }

我们使用泛型封装了BaseActivity和BasePresenter,接下来我们创建一个UserCenter个人中心登陆界面来使用一下我们的代码

interface LoginView : BaseView { fun loginResult(result: Boolean) } class LoginPresenter : BasePresenter<LoginView>() { fun login(account: String,password:String){ if (account == "admin" && password == "123456"){ mView.loginResult(true) }else{ mView.loginResult(false) } } } class LoginActivity : BaseMvpActivity<LoginPresenter>(), LoginView, View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) mPresenter = LoginPresenter() mPresenter.mView = this mLoginBtn.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.mLoginBtn -> { mPresenter.login(mAccountEt.text.toString(), mPassWordEt.text.toString()) } } } override fun loginResult(result: Boolean) { if (result) { toast("登陆成功") } else { toast("登陆失败") } } } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.kotlin.usercenter.ui.activity.LoginActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="账号" /> <EditText android:id="@+id/mAccountEt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码" /> <EditText android:id="@+id/mPassWordEt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> <Button android:id="@+id/mLoginBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="登陆" /> </LinearLayout>

到此我们MVP的简单封装就完成了,接下来我们将引入Dagger2,使用注入的方式来优化代码。 附上项目github地址

转载请注明原文地址: https://www.6miu.com/read-5032819.html

最新回复(0)