• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Android笔记Kotlin结合Jetpack构建MVVM

android 搞代码 3年前 (2022-03-01) 28次浏览 已收录 0个评论

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教程


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Android笔记Kotlin结合Jetpack构建MVVM

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址