四篇文章带你快速入门Jetpck(终)之Navigation,P

2021-01-08  本文已影响0人  Cache技术分享

四篇文章带你快速入门Jetpck(终)之Navigation,Paging

Jetpack

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

Android Architecture Component (AAC)

image.png

官方推荐架构

img

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

Navigation

Navigation的诞生

单个Activity嵌套多个Fragment的UI架构模式,已经被大多数Android工程师所接受和采用。但是,对Fragment的管理一直是一件比较麻烦的事情。

Navigation 的优点

添加依赖库

implementation "androidx.navigation:navigation-fragment:2.3.1"
implementation "androidx.navigation:navigation-ui:2.3.1"
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.1'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.1'

创建Navigation

  1. 创建Navigation Graph,nav_graph.xml

  2. 添加NavHostFragment

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />
    
    • android:name="androidx.navigation.fragment.NavHostFragment" ,特殊的Fragment。
    • app:defaultNavHost="true",系统自动处理返回键。
    • app:navGraph="@navigation/nav_graph",设置该Fragment对应的导航图。
  3. 创建destination

  4. 完成Fragment之间的切换

  5. 使用NavController完成导航

    btn_toSettingFragment.setOnClickListener {
     Navigation.findNavController(it).navigate(R.id.action_mainFragment_to_settingFragment)
    }
    
  6. 添加页面切换东华效果,创建anim文件夹,添加常用东华

    <action
        android:id="@+id/action_mainFragment_to_settingFragment"
        app:destination="@id/settingFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_right" />
    

Fragment传递参数

常见的传递参数的方式

val bundle = Bundle()
bundle.apply {
    putString("user_name", "yaoxin")
    putInt("age", 33)
}
Navigation.findNavController(it).navigate(R.id.action_mainFragment_to_settingFragment, bundle)

使用sate Arg传递参数

  1. 添加插件外层build.gradle
dependencies {
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.1"
}
  1. 添加依赖内层build.gradle
apply plugin: 'androidx.navigation.safeargs'
  1. 传递数据
val bundle = MainFragmentArgs.Builder().setUserName("yaoxin1").setAge(12).build().toBundle()
Navigation.findNavController(it).navigate(R.id.action_mainFragment_to_settingFragment, bundle)
  1. 获取数据
Log.d("SettingFragment", " username : ${arguments?.let { MainFragmentArgs.fromBundle(it).userName }}")
Log.d("SettingFragment", " age : ${arguments?.let { MainFragmentArgs.fromBundle(it).age }}")

NacvigationUI的使用

actionBar

  1. 添加menu.xml。

  2. 在Acitivity中重写onCreateOptionsMenu实例化菜单。

  3. 初始化,AppBarConfiguration,NavController类并使用NacvigationUI完成配置。

  4. 重写onOptionsItemSelected,onSupportNavigateUp方法,实现点击,页面切换。

  5. 实现addOnDestinationChangedListener接口,监听页面变化。

    navController.addOnDestinationChangedListener { _, _, _ ->
     Log.d("NavigationActivity", "页面发生了改变")
    }
    

DrawLayout + NavigationView 抽屉菜单

  1. 添加DrawerLayout布局

    <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/dl_drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
  1. 添加NavigationView控件

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nv_NavigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/menu_settings" />
    
  2. 使用NacvigationUI完成配置

    appBarConfiguration = AppBarConfiguration.Builder(navController.graph).setDrawerLayout(dl_drawerLayout).build()
    NavigationUI.setupWithNavController(nv_navigationView, navController)
    

ButtomNavigationView 底部菜单

  1. 添加BottomNavigationView控件

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bnv_bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/design_default_color_primary"
        app:itemTextColor="#FFFFFF"
        app:menu="@menu/menu_setting" />
    
  2. 使用NacvigationUI完成配置

    NavigationUI.setupWithNavController(bnv_bottomNavigationView, navController)
    

示例

NavigationActivity

class NavigationActivity : AppCompatActivity() {
    lateinit var appBarConfiguration: AppBarConfiguration
    lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_navigation)

        navController = Navigation.findNavController(this, R.id.nav_host_fragment)
        appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build()
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)

        navController.addOnDestinationChangedListener { _, _, _ ->
            Log.d("NavigationActivity", "页面发生了改变")
        }

        appBarConfiguration = AppBarConfiguration.Builder(navController.graph).setDrawerLayout(dl_drawerLayout).build()
        NavigationUI.setupWithNavController(nv_navigationView, navController)


        NavigationUI.setupWithNavController(bnv_bottomNavigationView, navController)

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        super.onCreateOptionsMenu(menu)
        menuInflater.inflate(R.menu.menu_setting, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return super.onOptionsItemSelected(item) || NavigationUI.onNavDestinationSelected(item, navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        return super.onSupportNavigateUp() || NavigationUI.navigateUp(navController, appBarConfiguration)
    }
}

activity_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/dl_drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".seventh.NavigationActivity">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_graph" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bnv_bottomNavigationView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@color/design_default_color_primary"
            app:itemTextColor="#FFFFFF"
            app:menu="@menu/menu_setting" />
    </RelativeLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nv_navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/menu_setting" />

</androidx.drawerlayout.widget.DrawerLayout>

MainFragment

class MainFragment : Fragment() {


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        btn_toSettingFragment.setOnClickListener {
            val bundle = Bundle()
            bundle.apply {
                putString("user_name", "yaoxin")
                putInt("age", 33)
            }
            val bundle1 = MainFragmentArgs.Builder().setUserName("yaoxin1").setAge(12).build().toBundle()


            Navigation.findNavController(it).navigate(R.id.action_mainFragment_to_settingFragment, bundle1)
        }
    }
}

SettingFragment

class SettingFragment : Fragment() {
    
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_setting, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val bundle = arguments
        if (bundle != null) {
            Log.d("SettingFragment", " username : ${bundle.getString("user_name")}")
            Log.d("SettingFragment", " age : ${bundle.getInt("age")}")

            Log.d("SettingFragment", " username : ${arguments?.let { MainFragmentArgs.fromBundle(it).userName }}")
            Log.d("SettingFragment", " age : ${arguments?.let { MainFragmentArgs.fromBundle(it).age }}")
        }
    }
}

menu_setting.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/mainFragment"
        android:title="主页" />
    <item
        android:id="@+id/settingFragment"
        android:title="设置" />
</menu>

nav_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.yx.androidseniorprepare.seventh.MainFragment"
        android:label="fragment_main"
        tools:layout="@layout/fragment_main">
        <action
            android:id="@+id/action_mainFragment_to_settingFragment"
            app:destination="@id/settingFragment"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right" />

        <argument
            android:name="user_name"
            android:defaultValue="unknown"
            app:argType="string" />
        <argument
            android:name="age"
            android:defaultValue="0"
            app:argType="integer" />
    </fragment>
    <fragment
        android:id="@+id/settingFragment"
        android:name="com.yx.androidseniorprepare.seventh.SettingFragment"
        android:label="fragment_setting"
        tools:layout="@layout/fragment_setting" />
</navigation>

Paging

Paging组件的意义

分页加载是在应用程序开发过程中十分常见的需求,我们经常需要以列表的形式加载大量的数据,这些数据通常来自网络或本地数据库。若一次加载大量的数据,这些数据消耗大量的时间和数据流量。

[图片上传失败...(image-19ef07-1610060544137)]

然而用户实际需要的可能只是部分数据,因此有了分页加载,分业加载按需加载,在不影响用户体验的同时,还能节省数据流量,提升应用性能。

数据来源

[图片上传失败...(image-8f3c85-1610060544137)]

工作原理

img
  1. 在RecyclerView的滑动过程中,会触发PagedListAdapter类中的onBindViewHolder()方法。数据与RecycleView中Item布局的UI控件正是在该方法中进行绑定的。
  2. 当RecyclerView滑动到底部时,在onBindViewHolder()方法中所调用的getItem()方法会通知PagedList,当前需要载入更多数据。
  3. 接着,PagedList会根据PageList.Config中的配置通知DataSource执行具体的数据获取工作。
  4. DataSource从网络/本地数据库取得数据后,交给PagedList,PagedList将持有这些数据。
  5. PagedList将数据交给PagedListAdapter中的DiffUtil进行比对和处理。
  6. 数据在经过处理后,交由RecyclerView进行展示。

Paging的3个核心类

  1. PagedListAdapter:
  1. PageList:
  1. DataSource

添加依赖权限

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation 'androidx.paging:paging-runtime-ktx:2.1.2'
 <uses-permission android:name="android.permission.INTERNET" />

3种DataSource

PositionalDataSource

PageKeyedDataSource

ItemKeyedDataSource

PositionalDataSource 使用

  1. 创建实体类

    data class Users(var page: Int, var page_count: Int, var total_counts: Int, var data: List<User>)
    
    data class User(var _id: String, var author: String, var createdAt: String, var url: String)
    
  2. 创建API接口

    interface Api {
        @GET("page/{page}/count/{count}")
        fun getUsers(@Path("page") page:Int,@Path("count") pageSize:Int):Call<Users>
    }
    
  3. 创建网络请求框架

    object RetrofitClient {
        private const val BASE_URL = "https://gank.io/api/v2/data/category/Girl/type/Girl/"
        private var retrofit: Retrofit? = null
    
        init {
            retrofit = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build()
        }
    
        fun getApi(): Api? {
            return retrofit?.create(Api::class.java)
        }
    }
    
  4. 创建UserDataSource继承PositionalDataSource

    class UserDataSource : PositionalDataSource<User>() {
    
        companion object {
            const val PER_PAGE = 10
            var startPosition = 1
        }
    
        override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<User>) {
    
            RetrofitClient
                .getApi()?.getUsers(startPosition, PER_PAGE)
                ?.enqueue(object : Callback<Users?> {
                    override fun onResponse(call: Call<Users?>, response: Response<Users?>) {
                        if (response.body() != null) {
                            Log.e(
                                "loadInitial()",
                                "startPosition:" + params.requestedStartPosition + " response:" + response.body()
                            )
                            callback.onResult(
                                response.body()!!.data,
                                response.body()!!.page,
                                response.body()!!.total_counts
                            )
                        }
                    }
    
                    override fun onFailure(call: Call<Users?>, t: Throwable) {
                        Log.e("loadInitial()", call.toString())
                    }
                })
        }
    
        override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<User>) {
            RetrofitClient
                .getApi()?.getUsers(startPosition + 1, PER_PAGE)
                ?.enqueue(object : Callback<Users?> {
                    override fun onResponse(call: Call<Users?>, response: Response<Users?>) {
                        if (response.body() != null) {
                            startPosition += 1
                            Log.e(
                                "loadRange()",
                                "startPosition:" + params.startPosition + " response:" + response.body()
                            )
                            callback.onResult(response.body()!!.data)
                        }
                    }
    
                    override fun onFailure(call: Call<Users?>, t: Throwable) {
                        Log.e("loadRange()", call.toString())
                    }
                })
        }
    
    }
    
  5. 创建UserDataSourceFactory负责创建UserDataSource,并使用LiveData包装UserDataSource讲其暴露给UserViewModel

    class UserDataSourceFactory : DataSource.Factory<Int, User>() {
        private val liveDataSource = MutableLiveData<UserDataSource>()
        override fun create(): DataSource<Int, User> {
            val dataSource = UserDataSource()
            liveDataSource.postValue(dataSource)
            return dataSource
        }
    }
    
  6. 创建ViewModel

    class UserViewModel : ViewModel() {
        var userPagedList: LiveData<PagedList<User>>? = null
    
        init {
            val config =
                PagedList.Config.Builder() // 是否显示占位。默认为true。当被设置为true时,要求在DataSource中提供数据源的总量,否则会报错。
                    // 这是因为RecyclerView需要知道数据总量,为这些数据预留位置
                    .setEnablePlaceholders(true)
                    //设置每页加载的数量
                    .setPageSize(UserDataSource.PER_PAGE)
                    //设置距离底部还有多少条数据时加载下一页数据
                    .setPrefetchDistance(0)
                    //重点,这里需要设置预获取的值>0,否则getKey()和loadBefore()以及loadAfter()不会被调用
                    //首次初始化加载的数量,需是分页加载数量的倍数。若没有设置,则默认是PER_PAGE的三倍
                    .setInitialLoadSizeHint(UserDataSource.PER_PAGE * 4)
                    //好像没有效果
                    //设置PagedList所能承受的最大数量,一般来说是PER_PAGE的许多许多倍,超过可能会出现异常。
                    .setMaxSize(65536 * UserDataSource.PER_PAGE).build()
    
            // 通过LivePagedListBuilder创建PagedList
            userPagedList = LivePagedListBuilder(UserDataSourceFactory(), config).build()
        }
        
    }
    
  7. 创建PagedListAdapter

    class UserAdapter(context: Context) : PagedListAdapter<User, UserAdapter.UserViewHolder>(DIFF_CALLBACK) {
        private var context: Context? = null
    
        init {
            this.context = context
        }
    
        companion object {
            /**
             * 用于计算列表中两个非空项之间的差异的回调。
             *
             * 之前数据更新了,需要通过notifyDataSetChanged()通知整个RecyclerView,效率不高
             * 使用DiffUtil只会更新需要更新的Item,不需要刷新整个RecyclerView,并且可以在Item删除的时候加上动画效果
             */
            private val DIFF_CALLBACK: DiffUtil.ItemCallback<User> = object : DiffUtil.ItemCallback<User>() {
                /**
                 * 当DiffUtil想要检测两个对象是否代表同一个Item时,调用该方法进行判断
                 */
                override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem._id == newItem._id
                }
    
                /**
                 * 当DiffUtil想要检测两个Item是否有一样的数据时,调用该方法进行判断
                 *
                 * 内容如果更新了,展示给用户看的东西可能也需要更新,所以需要这个判断
                 */
                override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem == newItem
                }
            }
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item_user, parent, false)
            return UserViewHolder(view)
        }
    
        override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
            val user = getItem(position)
            if (user != null) {
                Picasso.get().load(user.url).placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background).into(holder.ivAvatar)
                holder.tvName.text = user.author + " " + user.createdAt
            } else {
                holder.ivAvatar.setImageResource(R.drawable.ic_launcher_background)
                holder.tvName.text = ""
            }
        }
    
        class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var ivAvatar: ImageView = itemView.findViewById(R.id.iv_Avatar)
            var tvName: TextView = itemView.findViewById(R.id.tv_Name)
        }
    
    }
    

    xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="12dp">
    
        <ImageView
            android:id="@+id/ivAvatar"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentLeft="true" />
    
        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:gravity="left"
            android:layout_marginLeft="12dp"
            android:layout_toRightOf="@+id/ivAvatar"
            android:textSize="24sp" />
    
    </RelativeLayout>
    
  8. 配置Activity

    class PositionalDataSourceActivity : AppCompatActivity() {
        val TAG = this.javaClass.simpleName
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_positional_data_source)
            rv_recycler.layoutManager = LinearLayoutManager(this)
            rv_recycler.setHasFixedSize(true)
            val userAdapter = UserAdapter(this)
            val movieViewModel = ViewModelProviders.of(this)[UserViewModel::class.java]
            movieViewModel.userPagedList!!.observe(this, {
                Log.d(TAG, "onChange()->$it")
                userAdapter.submitList(it)
            })
            rv_recycler.adapter = userAdapter
            title = "PositionalDataSourceActivity"
        }
    }
    
  9. 效果图
    [图片上传失败...(image-896f07-1610060544137)]

PageKeyedDataSource使用

  1. 创建实体类

    data class User(var account_id: Int, var display_name: String?, var profile_image: String?)
    data class UserResponse(var items: List<User>?, var has_more: Boolean?)
    
  2. 创建API接口

    interface Api {
        @GET("users")
        fun getUsers(@Query("page") page: Int, @Query("pagesize") pageSize: Int, @Query("site") site: String): Call<UserResponse>
    }
    
  3. 创建网络请求框架

    object RetrofitClient {
        private const val BASE_URL = "https://api.stackexchange.com/2.2/"
        private var retrofit: Retrofit? = null
    
        init {
            retrofit = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build()
        }
    
        fun getApi(): Api? {
            return retrofit?.create(Api::class.java)
        }
    }
    
  4. 创建UserDataSource继承PageKeyedDataSource

    class UserDataSource : PageKeyedDataSource<Int, User>() {
    
        companion object {
            const val FIRST_PAGE = 1
            const val PER_PAGE = 10
            const val SITE = "stackoverflow"
        }
    
        override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, User>) {
            RetrofitClient.getApi()?.getUsers(FIRST_PAGE, PER_PAGE, SITE)?.enqueue(object : Callback<UserResponse> {
                override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
                    if (response.body() != null) {
                        Log.e("loadInitial()", " response:" + response.body())
                        response.body()!!.items?.toMutableList()?.let { callback.onResult(it, null, FIRST_PAGE + 1) }
    
                    }
                }
    
                override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                    TODO("Not yet implemented")
                }
            })
        }
    
        override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, User>) {
    
        }
    
        override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, User>) {
            Log.e("loadAfter()", "called");
            RetrofitClient.getApi()?.getUsers(params.key, PER_PAGE, SITE)?.enqueue(object : Callback<UserResponse> {
                override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
                    if (response.body() != null) {
                        Log.e("loadAfter()", " response:" + response.body())
                        val nextKey = if (response.body()!!.has_more!!) params.key + 1 else null
                        response.body()!!.items?.let { callback.onResult(it, nextKey) }
                    }
                }
    
                override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                    TODO("Not yet implemented")
                }
            })
        }
    
    
  5. 创建UserDataSourceFactory负责创建UserDataSource,并使用LiveData包装UserDataSource讲其暴露给UserViewModel

    class UserDataSourceFactory : DataSource.Factory<Int, User>() {
        private val liveDataSource = MutableLiveData<UserDataSource>()
        override fun create(): DataSource<Int, User> {
            val dataSource = UserDataSource()
            liveDataSource.postValue(dataSource)
            return dataSource
        }
    }
    
  6. 创建ViewModel

    class UserViewModel : ViewModel() {
        var userPagedList: LiveData<PagedList<User>>? = null
    
        init {
            val config = PagedList.Config.Builder() // 是否显示占位。默认为true。当被设置为true时,要求在DataSource中提供数据源的总量,否则会报错。
                    // 这是因为RecyclerView需要知道数据总量,为这些数据预留位置
                    .setEnablePlaceholders(true)
                    //设置每页加载的数量
                    .setPageSize(UserDataSource.PER_PAGE)
                    //设置距离底部还有多少条数据时加载下一页数据
                    .setPrefetchDistance(3)
                    //重点,这里需要设置预获取的值>0,否则getKey()和loadBefore()以及loadAfter()不会被调用
                    //首次初始化加载的数量,需是分页加载数量的倍数。若没有设置,则默认是PER_PAGE的三倍
                    .setInitialLoadSizeHint(UserDataSource.PER_PAGE * 3)
                    //好像没有效果
                    //设置PagedList所能承受的最大数量,一般来说是PER_PAGE的许多许多倍,超过可能会出现异常。
                    .setMaxSize(65536 * UserDataSource.PER_PAGE).build()
            // 通过LivePagedListBuilder创建PagedList
            userPagedList = LivePagedListBuilder(UserDataSourceFactory(), config).build()
        }
    }
    
  7. 创建PagedListAdapter

    class UserAdapter(context: Context) : PagedListAdapter<User, UserAdapter.UserViewHolder>(DIFF_CALLBACK) {
        private var context: Context? = null
    
        init {
            this.context = context
        }
    
        companion object {
            /**
             * 用于计算列表中两个非空项之间的差异的回调。
             *
             * 之前数据更新了,需要通过notifyDataSetChanged()通知整个RecyclerView,效率不高
             * 使用DiffUtil只会更新需要更新的Item,不需要刷新整个RecyclerView,并且可以在Item删除的时候加上动画效果
             */
            private val DIFF_CALLBACK: DiffUtil.ItemCallback<User> = object : DiffUtil.ItemCallback<User>() {
                /**
                 * 当DiffUtil想要检测两个对象是否代表同一个Item时,调用该方法进行判断
                 */
                override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem.account_id == newItem.account_id
                }
    
                /**
                 * 当DiffUtil想要检测两个Item是否有一样的数据时,调用该方法进行判断
                 *
                 * 内容如果更新了,展示给用户看的东西可能也需要更新,所以需要这个判断
                 */
                override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem == newItem
                }
            }
        }
    
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item_user, parent, false)
            return UserViewHolder(view)
        }
    
        override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
            val user = getItem(position)
            if (user != null) {
                Picasso.get().load(user.profile_image).placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background).into(holder.ivAvatar)
                holder.tvName.text = user.display_name
            } else {
                holder.ivAvatar.setImageResource(R.drawable.ic_launcher_background)
                holder.tvName.text = ""
            }
        }
    
        class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var ivAvatar: ImageView = itemView.findViewById(R.id.iv_Avatar)
            var tvName: TextView = itemView.findViewById(R.id.tv_Name)
    
        }
    
    }
    
  8. 配置Activity

    class PageKeyedDataSourceActivity : AppCompatActivity() {
        val TAG = this.javaClass.simpleName
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_page_keyed_data_source)
            rv_recycler.layoutManager = LinearLayoutManager(this)
            rv_recycler.setHasFixedSize(true)
            val userAdapter = UserAdapter(this)
            val movieViewModel = ViewModelProviders.of(this)[UserViewModel::class.java]
            movieViewModel.userPagedList!!.observe(this, {
                Log.e(TAG, "onChange()->$it")
                userAdapter.submitList(it)
            })
            rv_recycler.adapter = userAdapter
            title = "PageKeyedDataSourceActivity"
        }
    }
    
  9. 效果

[图片上传失败...(image-3f5622-1610060544137)]

ItemKeyedDataSource使用

  1. 创建实体类

    data class User(var id: Int, @SerializedName("login") var name: String?, @SerializedName("avatar_url") var avatar: String?)
    
  2. 创建API接口

    interface Api {
        @GET("users")
        fun getUsers(@Query("since") since: Int, @Query("per_page") perPage: Int): Call<List<User>>
    }
    
  3. 创建网络请求框架

    object RetrofitClient {
        private const val BASE_URL = "https://api.github.com/"
        private var retrofit: Retrofit? = null
    
        init {
            retrofit = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build()
        }
    
        fun getApi(): Api? {
            return retrofit?.create(Api::class.java)
        }
    }
    
  4. 创建UserDataSource继承ItemKeyedDataSource

    class UserDataSource : ItemKeyedDataSource<Int, User>() {
    
        companion object {
            const val PER_PAGE = 12
        }
    
        override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<User>) {
            Log.e("loadInitial()", "called")
            val since = 0
            RetrofitClient.getApi()?.getUsers(since, PER_PAGE)?.enqueue(object : Callback<List<User>> {
                override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
                    if (response.body() != null) {
                        Log.e("loadInitial()", " response:" + response.body())
                        callback.onResult(response.body()!!)
                    }
                }
    
                override fun onFailure(call: Call<List<User>>, t: Throwable) {
                    TODO("Not yet implemented")
                }
    
            })
        }
    
        override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<User>) {
            Log.e("loadAfter()", "called");
    
            RetrofitClient.getApi()?.getUsers(params.key, PER_PAGE)?.enqueue(object : Callback<List<User>> {
                override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
                    if (response.body() != null) {
                        Log.e("loadAfter()", " response:" + response.body())
                        callback.onResult(response.body()!!)
                    }
                }
    
                override fun onFailure(call: Call<List<User>>, t: Throwable) {
                    TODO("Not yet implemented")
                }
    
            })
        }
    
        override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<User>) {
            Log.e("loadBefore()", "called")
        }
    
        override fun getKey(item: User): Int {
            Log.e("getkey()", "called")
            return item.id
        }
    }
    
  5. 创建UserDataSourceFactory负责创建UserDataSource,并使用LiveData包装UserDataSource讲其暴露给UserViewModel

    class UserDataSourceFactory : DataSource.Factory<Int, User>() {
        private val liveDataSource = MutableLiveData<UserDataSource>()
        override fun create(): DataSource<Int, User> {
            val dataSource = UserDataSource()
            liveDataSource.postValue(dataSource)
            return dataSource
        }
    }
    
  6. 创建ViewModel

    class UserViewModel : ViewModel() {
        var userPagedList: LiveData<PagedList<User>>? = null
    
        init {
            val config = PagedList.Config.Builder() // 是否显示占位。默认为true。当被设置为true时,要求在DataSource中提供数据源的总量,否则会报错。
                    // 这是因为RecyclerView需要知道数据总量,为这些数据预留位置
                    .setEnablePlaceholders(true)
                    //设置每页加载的数量
                    .setPageSize(UserDataSource.PER_PAGE)
                    //设置距离底部还有多少条数据时加载下一页数据
                    .setPrefetchDistance(3)
                    //重点,这里需要设置预获取的值>0,否则getKey()和loadBefore()以及loadAfter()不会被调用
                    //首次初始化加载的数量,需是分页加载数量的倍数。若没有设置,则默认是PER_PAGE的三倍
                    .setInitialLoadSizeHint(UserDataSource.PER_PAGE * 3)
                    //好像没有效果
                    //设置PagedList所能承受的最大数量,一般来说是PER_PAGE的许多许多倍,超过可能会出现异常。
                    .setMaxSize(65536 * UserDataSource.PER_PAGE).build()
    
            // 通过LivePagedListBuilder创建PagedList
            userPagedList = LivePagedListBuilder(UserDataSourceFactory(), config).build()
        }
    }
    
  7. 创建PagedListAdapter

    class UserAdapter(context: Context) : PagedListAdapter<User, UserAdapter.UserViewHolder>(DIFF_CALLBACK) {
        private var context: Context? = null
    
        init {
            this.context = context
        }
    
        companion object {
            /**
             * 用于计算列表中两个非空项之间的差异的回调。
             *
             * 之前数据更新了,需要通过notifyDataSetChanged()通知整个RecyclerView,效率不高
             * 使用DiffUtil只会更新需要更新的Item,不需要刷新整个RecyclerView,并且可以在Item删除的时候加上动画效果
             */
            private val DIFF_CALLBACK: DiffUtil.ItemCallback<User> = object : DiffUtil.ItemCallback<User>() {
                /**
                 * 当DiffUtil想要检测两个对象是否代表同一个Item时,调用该方法进行判断
                 */
                override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem.id == newItem.id
                }
    
                /**
                 * 当DiffUtil想要检测两个Item是否有一样的数据时,调用该方法进行判断
                 *
                 * 内容如果更新了,展示给用户看的东西可能也需要更新,所以需要这个判断
                 */
                override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
                    return oldItem == newItem
                }
            }
        }
    
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item_user, parent, false)
            return UserViewHolder(view)
        }
    
        override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
            val user = getItem(position)
            if (user != null) {
                Picasso.get().load(user.avatar).placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background).into(holder.ivAvatar)
                holder.tvName.text = user.name
            } else {
                holder.ivAvatar.setImageResource(R.drawable.ic_launcher_background)
                holder.tvName.text = ""
            }
        }
    
        class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var ivAvatar: ImageView = itemView.findViewById(R.id.iv_Avatar)
            var tvName: TextView = itemView.findViewById(R.id.tv_Name)
    
        }
    
    }
    
  8. 配置Activity

    class ItemKeyedDataSourceActivity : AppCompatActivity() {
        val TAG = this.javaClass.simpleName
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_item_keyed_data_source)
            rv_recycler.layoutManager = LinearLayoutManager(this)
            rv_recycler.setHasFixedSize(true)
            val userAdapter = UserAdapter(this)
            val movieViewModel = ViewModelProviders.of(this)[UserViewModel::class.java]
            movieViewModel.userPagedList!!.observe(this, {
                Log.e(TAG, "onChange()->$it")
                userAdapter.submitList(it)
            })
            rv_recycler.adapter = userAdapter
            title = "ItemKeyedDataSourceActivity"
        }
    }
    
  9. 效果
    [图片上传失败...(image-f7efec-1610060544137)]

项目代码
项目视频

上一篇下一篇

猜你喜欢

热点阅读