After introducing the background and original intention, we started to build the FRAMEWORK of MVVM. In this part, we carried out simple construction to understand the basic structure of MVVM architecture.

MVVM framework construction (a) – background

The construction of MVVM framework (ii) – project construction

The construction of MVVM framework (three) — network request

MVVM data persistence (I) — ROOM integration

MVVM data persistence (2) — use of ROOM

Creating a new project

First create a new project and create a config.gradle figure in the root directory

/** * config.gradle is used to configure lib references and version control for projects ** [module_*] Module version and applicationId control * Please use module_ [modulename] * * * naming rules [project. Ext dependVersion] created in all dependent libraries of version control, Create maven addresses for each class library by adding '_version' * * [class library maven address] to the name of the class library. If the same class library needs to reference more than one class, you can use an array. Make sure that the class library reference does not duplicate the dependency list created in * * [project dependency list] that can be referenced directly by module. * Do not name the dependency list after the name of the class library * * Use the item in the project dependency list when referring to the class library in each module. Do not use the item directly in the address of the class library. * * When adding a new class library, Check this list and the project to see if there are libraries that reference similar functionality */ project.ext {compileSdkVersion = 27 buildToolsVersion ='27.0.3'MinSdkVersion = 16 targetSdkVersion = 27 // Main app module_appApplicationId ='yang.cehome.com.mvvmdemo'
    module_appVersionCode = 0001
    module_appVersionName = '1.0.0'
    module_appName = 'MVVM'DependVersion = [kotlin_version:'1.2.51',
            support_version: '27.1.1'] / / * * * * * * * * * * * * * * * * * * * * * * * * * class library maven address * * * * * * * * * * * * * * * * * * * * * * * * * * kotlin_base = [kotlin_stdlib_jdk8:"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$dependVersion.kotlin_version"]
    supportLibs = [
            design      : "com.android.support:design:$dependVersion.support_version",
            appcompat_v7: "com.android.support:appcompat-v7:$dependVersion.support_version",
            constraint  : 'com. Android. Support. The constraint, the constraint - layout: 1.1.3'] / / * * * * * * * * * * * * * * * * * * * * project depend on the list of * * * * * * * * * * * * * * * * * * * * * * kotlinDeps = [kotlin_base. Values ()] supportDeps = [supportLibs.values()] }Copy the code

Then build. Gradle. We reference the corresponding library

Depend on the way

After AndroidStudio was upgraded to 3.0, gradle was also upgraded to 3.0.0. Since then, the way you notice dependencies has changed a bit, which is briefly described here

Writing in the front

MVC MVP MVVM framework is now introduced a lot, a lot of online search will not focus on the introduction. So this time we will focus on the MVVM framework. Here we start using Kotlin and follow Google’s App Development Architecture guide to find a better way to build MVVM applications. First: What is MVVM? MVVM is short for Model-view-ViewModel, which is another architectural pattern distinct from MVC and MVP. Compared to MVP, MVVM has no additional callbacks, and the Databinding framework binds the data in the ViewModel to the UI, allowing developers to change the UI simply by updating the data in the ViewModel.

● The Model layer is responsible for providing data sources to the ViewModel, including entity classes, network requests, and local storage. ● The ViewModel layer is responsible for providing data sources to the ViewModel. ● View: Activity, Fragment, layout.xml, Adapter, custom View, etc., responsible for connecting the three.

Another benefit is that you can do unit testing, which is very comfortable to write in pure Kotlin code and ensures that the data is correct. Compared with running app, which takes tens of seconds or minutes, running a unit test is recorded in milliseconds, which is quite efficient.

Code implementation

First we create a class

/**
 * @author yangzc
 *	@data 2018/9/6 13:58
 *	@desc
 *
 */
class Onclick(val who: String, val count: Int)
Copy the code
We used to write code for a click event about
Layout file
<? xml version="1.0" encoding="utf-8"? > <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="yang.cehome.com.mvvmdemo.MainActivity">

    <Button
        android:id="@+id/bt_onclick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="onclick"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="100dp"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Copy the code
This is implemented in an Activity
package yang.cehome.com.mvvmdemo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val onclik = Onclick("my", 0)
        tv_count.text = "${onclik.who}Click on the${onclik.count}Time. ""
        bt_onclick.setOnClickListener(View.OnClickListener {
            onclik.count++
            tv_count.text = "${onclik.who}Click on the${onclik.count}Time. ""}}})Copy the code

I’m going to implement a click event and display code that we usually write whereas if we’re going to use the MVVM framework it’s obviously not going to do that first let’s look at the architecture

3. The ViewModel layer is responsible for providing data sources to the ViewModel, including entity classes, network requests, and local storage. Activity, Fragment, layout. XML, Adapter, custom View, etc., are responsible for connecting the three together. After a brief introduction to MVVM, after creating the project, have a look at the structure

Based on the Demo

Let’s according to our said before to write a simple Demo first have a look at the structure of package DataBindingUtil, the setContentView this function did three operations:

  • The inflate operation creates the view object corresponding to the layout file
  • The setContentView operation adds the view to the window
  • Bind (view, bindingComponent) calls ActivityXxxBinding. Bind (View, bindingComponent) then calls: New ActivityXxxBinding(bindingComponent, View) creates an ActivityXxxBinding object. // enable dataBinding dataBinding{enabled = true} let’s look at the layout file. In fact, we can see that in MVVM the layout file is more than just a UI effect.
<? xml version="1.0" encoding="utf-8"? > <layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"> <data> <! Mbinding. vm=mViewMode --> <variable name="vm"
            type="yang.cehome.com.mvvmdemo.viewmodel.OnclikViewModel" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".view.MainActivity">


        <Button
            android:id="@+id/bt_onclick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{()->vm.click()}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Give it a try." />

        <TextView
            android:id="@+id/tv_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="100dp"
            android:text="@{vm.info}"
            android:textSize="16sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Zero times." />

    </android.support.constraint.ConstraintLayout>
</layout>
Copy the code

A few points to note:

2. Added a data tag that our ViewModel injected by binding 3. Add corresponding methods to each control and let’s look at the data that the M layer code provides to the ViewModel layer

/ * * * @ the author package yang.cehome.com.mvvmdemo.model yangzc * @ data 2018/9/6 13:58 * @ desc data Model (MVVM * */ class Onclick(val who: String, var count: Int)Copy the code

Now we’re going to look at the ViewModel layer which is basically responsible for handling the data and providing the data to the View layer and the ViewModel is used to store and manage uI-related data.

package yang.cehome.com.mvvmdemo.viewmodel import android.databinding.ObservableField import / * * * @ yang.cehome.com.mvvmdemo.model.Onclick author yangzc * @ data 2018/9/6 for * @ desc processing data V (MVVM * */ class OnclikViewModel(val onlick: Onclick) { /******data******/ val info = ObservableField<String>("\"${onlick.who}Click on the${onlick.count}Time \ "")

    /******binding******/
    fun click() {
        onlick.count++
        info.set("\"${onlick.who}Click on the${onlick.count}Time \ "")}}Copy the code

Finally, let’s look at the View layer, which is our Activity and Fragment

package yang.cehome.com.mvvmdemo.view import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import yang.cehome.com.mvvmdemo.R import yang.cehome.com.mvvmdemo.databinding.ActivityMainBinding import yang.cehome.com.mvvmdemo.model.Onclick import Yang.cehome.com.mvvmdemo.viewmodel.OnclikViewModel / * * * a V layer of MVVM link three * / class MainActivity:AppCompatActivity() {
    private lateinit var mBinding: ActivityMainBinding
    private lateinit var mViewMode: OnclikViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        /////model
        val onclick = Onclick("me", 0)
        ///ViewModel
        mViewMode = OnclikViewModel(onclick)
        ///binding
        mBinding.vm = mViewMode
    }
}
Copy the code

The above is a simple MVVM framework

The project address

Github.com/yang0range/…