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

Jetpack

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

Android Architecture Component (AAC)。

官方推荐架构

【Android笔记】Kotlin结合Jetpack构建MVVM_第1张图片

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

MVVM

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

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

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

API接口

接口:https://api.github.com/users/...

工程结构

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
}
```
####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
}
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 {
        refresh(name)
        return userDao.getUserByName(name)
    }

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

            override fun onFailure(call: Call, 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



    

        
    

    

        

            

            

            

            

            

            

            

            
        
    
10. 在Activity触发事件
class MvvmActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding =
            DataBindingUtil.setContentView(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教程

你可能感兴趣的:(【Android笔记】Kotlin结合Jetpack构建MVVM)