【Android笔记】Kotlin结合Jetpack构建MVVM

669 阅读2分钟

Jetpack

Jetpack 是一个由多个库组成的套件,可帮助开发者遵循最佳做法,减少样板代码并编写可在各种 Android 版本和设备中一致运行的代码,让开发者精力集中编写重要的代码。

Android Architecture Component (AAC)。

官方推荐架构

73bd0ed878dd68c2ee1511da5862d662.png

请注意,每个组件仅依赖于其下一级的组件。例如,Activity 和 Fragment 仅依赖于视图模型。存储区是唯一依赖于其他多个类的类;在本例中,存储区依赖于持久性数据模型和远程后端数据源。

MVVM

MVVM即Model - View - ViewModel的缩写,它的出现是为了将图形界面与业务逻辑,数据模型进行解耦。

MVVM也是Google推崇的一种Android项目架构模型。

之前学习的Jetpack组建,大部分都是为了能够更好地架构MVVM应用程序而设计的。

API接口

接口:api.github.com/users/yaoxi…

工程结构

bean:实体类。
api:网络请求接口。
repository:仓储层。用于存放Room数据,网络数据,本地数据等。
viewmodel:从仓储层获取数据,不需要关心数据来源。
view:Activity,Fragment和布局文件,用会用到DataBinding组件
dao:Room数据库操作
application:实例化全局文件和获取全局上下文。
bindingAdapter:放一些

添加依赖

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'de.hdodenhof:circleimageview:3.0.1'

搭建项目

通过获取GitHub API获取个人信息进行展示。

1. 定义User实体类
@Entity(tableName = "user")
data class User(
    @PrimaryKey @ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER) var id: Int,
    @ColumnInfo(name = "login", typeAffinity = ColumnInfo.TEXT) var login: String,
    @ColumnInfo(name = "name", typeAffinity = ColumnInfo.TEXT) var name: String?,
    @ColumnInfo(name = "avatar_url", typeAffinity = ColumnInfo.TEXT) @SerializedName("avatar_url")var avatar: String?,
    @ColumnInfo(name = "blog", typeAffinity = ColumnInfo.TEXT) var blog: String,
    @ColumnInfo(name = "company", typeAffinity = ColumnInfo.TEXT) var company: String?,
    @ColumnInfo(name = "bio", typeAffinity = ColumnInfo.TEXT) var bio: String?,
    @ColumnInfo(name = "location", typeAffinity = ColumnInfo.TEXT) var location: String?,
    @ColumnInfo(name = "htmlUrl", typeAffinity = ColumnInfo.TEXT) @SerializedName("html_url") var htmlUrl: String?
)
2. 定义Dao类
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertUser(user: User)

    @Delete
    fun deleteUser(user: User)

    @Query("select * from user where login =:name")
    fun getUserByName(name: String): LiveData<User>
}
3. 定义DataBase类
@Database(entities = [User::class], version =7)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        private var instance: AppDatabase? = null

        @Synchronized
        fun getDatabase(context: Context): AppDatabase {
            instance?.let {
                return it
            }
            return Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                "user_db"
            ).fallbackToDestructiveMigration().build().apply {
                instance = this
            }
        }
    }
}

4. 定义API接口

interface Api {
    @GET("users/{userName}")
    fun getUser(@Path("userName") userName: String): Call<User>
}
5. 定义Retrofit访问网络
object RetrofitClient {
    private const val BASE_URL = "https://api.github.com/"
    var retrofit: Retrofit

    init {
        retrofit =
            Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
                .build()
    }

    fun getApi(): Api? {
        return retrofit.create(Api::class.java)
    }
}
6. 定义Application类
class MyApplication : Application() {
    companion object {
        lateinit var context: Context
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
    }
}
7. 定义Repository
object UserRepository {
    var userDao: UserDao = AppDatabase.getDatabase(MyApplication.context).userDao()

    fun getUser(name: String): LiveData<User> {
        refresh(name)
        return userDao.getUserByName(name)
    }

    fun refresh(name: String) {
        RetrofitClient.getApi()?.getUser(name)?.enqueue(object : Callback<User> {
            override fun onResponse(call: Call<User>, response: Response<User>) {
                if (response.body() != null) {
                    insertUser(response.body()!!)
                }
            }

            override fun onFailure(call: Call<User>, t: Throwable) {
                Log.d("UserRepository", "onFailure$t")
            }

        })
    }

    fun insertUser(user: User) {
        thread {
            userDao.insertUser(user)
        }
    }
}
8. 定义ViewModel
class MvvmViewModel : ViewModel() {
    val userName = "yaoxin521123"
    fun getUser() = UserRepository.getUser(userName)
    fun refresh() = UserRepository.refresh(userName)
}
9. 绘制xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="user"
            type="com.yx.androidseniorpreparetest.eighth.bean.User" />
    </data>

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/srl_SwipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".eighth.MvvmActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="95dp"
                android:layout_height="95dp"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                app:image="@{user.avatar}" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.name}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.login}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.blog}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.company}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.bio}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.location}"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:text="@{user.htmlUrl}"
                android:textColor="#000000"
                android:textSize="20sp" />
        </LinearLayout>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout
</layout>
10. 在Activity触发事件
class MvvmActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding =
            DataBindingUtil.setContentView<ActivityMvvmBinding>(this, R.layout.activity_mvvm)
        val viewModel = ViewModelProviders.of(this).get(MvvmViewModel::class.java)
        viewModel.getUser().observe(this, {
            if (it != null) {
                binding.user = it
            }
        })
        binding.srlSwipeRefreshLayout.setOnRefreshListener {
            viewModel.refresh()
            binding.srlSwipeRefreshLayout.isRefreshing = false
        }

    }
}
11. 定义BindingAapter
class BindingAdapter {
    companion object {
        @JvmStatic
        @BindingAdapter(value = ["image", "defaultImageResource"], requireAll = false)
        fun setImage(imageView: ImageView, imageUrl: String?, imageResource: Int) {
            if (!TextUtils.isEmpty(imageUrl)) {
                Picasso.get()
                    .load(imageUrl)
                    .placeholder(R.drawable.ic_launcher_background)
                    .error(R.drawable.ic_launcher_background)
                    .into(imageView)
            } else {
                imageView.setImageResource(imageResource)
            }
        }
    }
}

结语:后续会持续更新哦,喜欢的话点赞关注一下吧。
相关视频
【Android进阶】jetpack教程