Android (Kotlin version) MVC framework examples and code

Android (Kotlin version) MVC framework examples and code

  The address of this article: https://blog.csdn.net/qq_40785165/article/details/112135944 ,
  it may be boring to reprint the address and the code may be boring, but creation can always make people feel heartbroken. This is probably enthusiasm!
  Hello everyone, I am Xiaohei, a programmer who is not yet bald~~~ I have been
  busy recently, but I can’t forget my original intention of writing this article, which is to record my learning and changes over a period of time. Today’s content is Android development. MVC framework design. Since I am learning kotlin recently, this article will use kotlin as the development language. First, let’s take a look at
MvcDemo dynamic map
  the function in the rendering demo. The function is very simple. It is a simulated login process, and the data interface development list is called after successful login. , Because I want to write the MVC architecture together with the data request, and want to save space, so the code for the login module is not posted, here only the design code of the list is shown, students who want other codes can go to the github address of the Demo manually Download, not much to say, the text begins below.
  The MVC framework consists of the following three parts: Model| (model layer), View (view layer), Controller (control layer)
1. Model: Responsible for requesting the interface, processing data, and reporting the results to the Controller layer through callbacks and updating the view .
2. View: view design, here generally refers to the xml view code in the layout.
3. Controller: control layer, usually refers to Activity/Fragment, holds Model objects, and updates the UI by listening to Model state changes. The
project structure is shown in the figure. :


(1) First design the view xml file, that is, the View layer, the activity_wechat_official_account.xml code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

  The code of the item_office_account.xml of the list item is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
</LinearLayout>

(2) Design the Activity code, namely the Controller layer, the WeChatOfficialAccountListActivity.kt code is as follows:

class WeChatOfficialAccountListActivity : AppCompatActivity(), WeChatOfficeAccountListener {
    private val mList: MutableList<OfficeAccountBean> = ArrayList()
    private val weChatOfficeAccountModel by lazy {
        WeChatOfficeAccountModel()
    }
    private val weChatOfficialAccountAdapter by lazy {
        WeChatOfficialAccountAdapter(this, mList)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wechat_official_account)
        rv_list.layoutManager = LinearLayoutManager(this)
        rv_list.adapter = weChatOfficialAccountAdapter
        weChatOfficeAccountModel.loadData(this)
    }

    override fun onLoading() {
        Toast.makeText(this, "正在加载中", Toast.LENGTH_SHORT).show()
    }

    override fun onLoadSuccess(list: MutableList<OfficeAccountBean>?) {
        runOnUiThread(Thread {
            Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show()
            if (list != null && list.size > 0) {
                mList.addAll(list)
            }
            weChatOfficialAccountAdapter.notifyDataSetChanged()
        })


    }

    override fun onLoadFail(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}

  It can be known from the code that the Controller layer holds a Model object and implements an interface, which implements callbacks, and updates the UI of the main thread through callbacks. The code of the child adapter WeChatOfficialAccountAdapter.kt of the list is as follows:

class WeChatOfficialAccountAdapter(var context: Context, var list: MutableList<OfficeAccountBean>) :
    RecyclerView.Adapter<WeChatOfficialAccountAdapter.ViewHolder>() {
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var tvName: TextView = view.findViewById(R.id.tv_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_office_account,
                null,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.tvName.text = list[position].name
    }
}

  The callback interface WeChatOfficeAccountListener.kt code is as follows:

interface WeChatOfficeAccountListener {
    fun onLoading()
    fun onLoadSuccess(list: MutableList<OfficeAccountBean>? = null)
    fun onLoadFail(msg: String? = "")
}

(3) Design the Model layer, implement data processing, call interfaces and other operations, and notify the control layer to update the UI through a callback. The WeChatOfficeAccountModel.kt code is as follows:

class WeChatOfficeAccountModel {
    private val weChatOfficeAccountApi by lazy {
        WeChatOfficeAccountApi()
    }

    fun loadData(callback: WeChatOfficeAccountListener) {
        weChatOfficeAccountApi.loadData(callback)
    }
}

  There is no interface call, data processing and other operations in my Model layer. That's because I put the call interface in the WeChatOfficeAccountApi.kt file. The code is as follows:

class WeChatOfficeAccountApi {
    private val gson by lazy {
        GsonBuilder().serializeNulls().create()
    }

    fun loadData(callback: WeChatOfficeAccountListener) {
        callback.onLoading()
        //拿到OkhttpClient对象
        var okHttpClient = OkHttpClient()
        //构造request对象,get方式,传入接口地址
        var url = Request.Builder()
            .get()
            .url("https://wanandroid.com/wxarticle/chapters/json")
            .build()
        var newCall = okHttpClient.newCall(url)
        newCall.enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                callback.onLoadFail()
            }

            override fun onResponse(call: Call?, response: Response?) {
                var string = response?.body()?.string()
                Log.e("Tag", string)
                var result = gson.fromJson<DataResult<MutableList<OfficeAccountBean>>>(
                    string,
                    object : TypeToken<DataResult<MutableList<OfficeAccountBean>>>() {}.type
                )
                Log.e("Tag", result.toString())
                callback.onLoadSuccess(result.data)
            }
        })
    }
}

  In the above code, if you don’t like this way of writing, you can also call the interface directly in the Model. It varies from person to person. The interface called is the open interface of playing Android , the okhttp network request framework is used, and gson is used to parse the data. The libraries are:

    implementation 'com.squareup.okhttp3:okhttp:3.5.0'
    implementation 'com.google.code.gson:gson:2.8.6'

  The required permissions are:

<uses-permission android:name="android.permission.INTERNET" />

  Ok, so far, the Android MVC framework has been built. This is my personal understanding and practice of MVC. If you have different opinions or suggestions, please comment below. We make progress together. The renderings and source code are at the beginning! Finally, I wish you all a happy new year and joy every year!

Guess you like

Origin blog.csdn.net/qq_40785165/article/details/112135944