关于android:Android笔记Kotlin结合Jetpack构建MVVM

51次阅读

共计 6793 个字符,预计需要花费 17 分钟才能阅读完成。

Jetpack

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

Android Architecture Component (AAC)。

官网举荐架构

请留神,每个组件仅依赖于其下一级的组件。例如,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<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 教程

正文完
 0