欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android Jetpack- Paging的使用詳解

 更新時間:2020年11月06日 10:56:34   作者:梁景杰Android  
這篇文章主要介紹了Android Jetpack- Paging的使用詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

Google 推出 Jetpack 組件化已經(jīng)有相當(dāng)一段時間了。各種組件也層出不窮。

     Jetpack 的東西也不少,

    

     今天就搞一下這個  Paging

     Paging 的出現(xiàn),就是用作列表的分頁加載。其實現(xiàn)在已經(jīng)有非常多成熟高效的開源列表加載控件了,比如:Smartrefreshlayout等。但Google推出的,必然有它的有點,當(dāng)然也有它的局限性。

     先說優(yōu)點吧,Paging 的使用,需要配合ViewModle,LiveData等控件,數(shù)據(jù)的請求感知并綁定頁面的生命周期,避免了內(nèi)存泄漏。還需要綁定DataSource和DataSource的Factory,能無痕加載更多數(shù)據(jù),一定程度上提高用戶體驗。

    主要流程是:

     1:自定義 PositionalDataSource,里面的功能是進(jìn)行數(shù)據(jù)分頁請求。

     2:自定義 DataSource.Factory,把 PositionalDataSource 綁定 LiveData

     3:Activity 自定義 ViewModel,把 PositionalDataSource 和 Factory 綁定,讓 ViewModel 感知數(shù)據(jù)的變化 

     4:ViewModel感知數(shù)據(jù)的變更,并更新  PagedListAdapter 的 submitList。

最先看看導(dǎo)入那些依賴:

 implementation "androidx.paging:paging-runtime:3.0.0-alpha04"
  implementation 'androidx.recyclerview:recyclerview:1.1.0'
  implementation 'com.squareup.retrofit2:retrofit:2.9.0'
  implementation "android.arch.lifecycle:extensions:1.1.1"

【1】先看 Activity 代碼: 

class MainActivity : AppCompatActivity() {
 
 
 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
 
  val myPagedListAdapter = MyPagedListAdapter()
  recyclerView.layoutManager = LinearLayoutManager(this)
  recyclerView.adapter = myPagedListAdapter
 
  /**
   *  ViewModel 綁定 Activity 生命周期
   * */
  val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
 
  /**
   *  ViewModel 感知數(shù)據(jù)變化,更新 Adapter 列表
   * */
  myViewModel.getConvertList().observe(this, Observer {
   myPagedListAdapter.submitList(it)
  })
 }
 
}

  【2】看 Adapter代碼:

             這里要用的是 PagedListAdapter,其實它是繼承了 RecyclerView.Adapter 的,所以用起來沒和 RecyclerView.Adapter 多大區(qū)別,就是多了一個內(nèi)部需要實現(xiàn) DiffUtil.ItemCallback 來。具體 DiffUtil.ItemCallback 的原理就不在這說了,博主也沒有細(xì)究,它是用來比較數(shù)據(jù)的。其內(nèi)部實現(xiàn)方法也基本上可以寫死。

class MyPagedListAdapter extends PagedListAdapter<MyDataBean, MyViewHolder> {
 
 
 private static DiffUtil.ItemCallback<MyDataBean> DIFF_CALLBACK =
   new DiffUtil.ItemCallback<MyDataBean>() {
    @Override
    public boolean areItemsTheSame(MyDataBean oldConcert, MyDataBean newConcert) {
     // 比較兩個Item數(shù)據(jù)是否一樣的,可以簡單用 Bean 的 hashCode來對比
     return oldConcert.hashCode() == newConcert.hashCode();
    }
 
    @Override
    public boolean areContentsTheSame(MyDataBean oldConcert,
             MyDataBean newConcert) {
     // 寫法基本上都這樣寫死即可
     return oldConcert.equals(newConcert);
    }
   };
 
 
 public MyPagedListAdapter() {
  // 通過 構(gòu)造方法 設(shè)置 DiffUtil.ItemCallback 
  super(DIFF_CALLBACK);
 }
 
 @NonNull
 @Override
 public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_my, parent, false);
  return new MyViewHolder(inflate);
 }
 
 @Override
 public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
  // getItem() 是 PagedListAdapter 內(nèi)部方法,通過此方法可以獲取到對應(yīng)位置Item 的數(shù)據(jù)
  holder.bindData(getItem(position));
 }
 
}

順便也把 ViewHolder 和  MyDataBean 貼一下

ViewHolder :

class MyViewHolder(val itemV: View) : RecyclerView.ViewHolder(itemV) {
 
 fun bindData(data: MyDataBean) {
  itemV.findViewById<TextView>(R.id.tvNum).text = data.position.toString()
 
  if (data.position % 2 == 0){
   itemV.findViewById<TextView>(R.id.tvNum).setBackgroundColor(itemV.context.resources.getColor(R.color.colorAccent))
  }else{
   itemV.findViewById<TextView>(R.id.tvNum).setBackgroundColor(itemV.context.resources.getColor(R.color.colorPrimaryDark))
  }
 }
}

MyDataBean :

data class MyDataBean(val position: Int)

  【3】看 DataSource 代碼:

PositionalDataSource,里面的功能是進(jìn)行數(shù)據(jù)分頁請求。

需要實現(xiàn)兩個方法:

loadInitial():第一次打開頁面,需要回調(diào)此方法來獲取數(shù)據(jù)

loadRange():  當(dāng)有了初始化數(shù)據(jù)之后,滑動的時候如果需要加載數(shù)據(jù)的話,會調(diào)用此方法。

class MyDataSource : PositionalDataSource<MyDataBean>() {
 
 /**
  * 第一次打開頁面,需要回調(diào)此方法來獲取數(shù)據(jù)
  * */
 override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<MyDataBean>) {
  // 獲取網(wǎng)絡(luò)數(shù)據(jù)
  val list = getData(params.requestedStartPosition, params.pageSize)
  /**
   *  這個方法是返回數(shù)據(jù),讓 綁定ViewModel 感知。 這里要用對方法
   *  @param1 數(shù)據(jù)列表
   *  @param2 數(shù)據(jù)為起始位置
   *  @param3 數(shù)據(jù)列表總長度,這個一定要設(shè)置好哦,如果設(shè)置了50,
   *    當(dāng)列表的長度為50時,列表再也無法出發(fā) loadRange() 去加載更多了
   *    如果不知道列表總長度,可以設(shè)置 Int 的最大值 999999999
   *    這里設(shè)置 10000
   * */
  callback.onResult(list, 0, 10000)
 }
 
 /**
  * 當(dāng)有了初始化數(shù)據(jù)之后,滑動的時候如果需要加載數(shù)據(jù)的話,會調(diào)用此方法。
  * */
 override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MyDataBean>) {
  /**
   *  params.startPosition 列表需要從 startPosition 加載更多
   *  params.loadSize  列表需要從 startPosition 加載長度 為 loadSize的數(shù)據(jù)
   * */
  val list = getData(params.startPosition, params.loadSize)
  callback.onResult(list)
 }
 
 /**
  * 模擬網(wǎng)絡(luò)獲取數(shù)據(jù)
  * */
 private fun getData(startPosition: Int, pageSize: Int): MutableList<MyDataBean> {
 
  
  Handler(Looper.getMainLooper()).post {
   Toast.makeText(
    MyApplication.instant,
    "加載數(shù)據(jù) 從 $startPosition 加載到 ${startPosition + pageSize}",
    Toast.LENGTH_SHORT
   ).show()
  }
 
  val list = mutableListOf<MyDataBean>()
  for (i in startPosition until startPosition + pageSize) {
   list.add(MyDataBean(i))
  }
  return list
 }
}

【4】看 DataSource.Factory代碼:

把 PositionalDataSource 綁定 LiveData

class DataFactory: DataSource.Factory<Int, MyDataBean>() {
 
 private val mSourceLiveData: MutableLiveData<MyDataSource> =
  MutableLiveData<MyDataSource>()
 
 override fun create(): DataSource<Int, MyDataBean> {
  val myDataSource = MyDataSource()
  mSourceLiveData.postValue(myDataSource)
  return myDataSource
 }
 
}

  【5】最后看 ViewModel代碼:

class MyViewModel : ViewModel() {
 
 private var mDataSource : DataSource<Int, MyDataBean>
 private var mDataList: LiveData<PagedList<MyDataBean>>
 
 init {
  // 把 PositionalDataSource 和 Factory 綁定,讓 ViewModel 感知數(shù)據(jù)的變化
  var dataFactory = DataFactory()
  mDataSource = dataFactory.create()
  /**
   *  @param1 dataFactory 設(shè)定 dataFactory
   *  @param2 設(shè)定每一次加載的長度 
   *    這個和 PositionalDataSource 回調(diào)方法 loadSize 一致的
   * */ 
  mDataList = LivePagedListBuilder(dataFactory, 20).build()
 }
 
 // 暴露方法,讓Activity 感知數(shù)據(jù)變化,去驅(qū)動 Adapter更新列表
 fun getConvertList(): LiveData<PagedList<MyDataBean>> {
  return mDataList
 }
}

【5】最后再看一下  Activity 代碼:

class MainActivity : AppCompatActivity() {
 
 
 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
 
  val myPagedListAdapter = MyPagedListAdapter()
  recyclerView.layoutManager = LinearLayoutManager(this)
  recyclerView.adapter = myPagedListAdapter
 
  /**
   *  ViewModel 綁定 Activity 生命周期
   * */
  val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
 
  /**
   *  ViewModel 感知數(shù)據(jù)變化,更新 Adapter 列表
   * */
  myViewModel.getConvertList().observe(this, Observer {
   myPagedListAdapter.submitList(it)
  })
 }
 
}

貼一下  activity_main.xml 的代碼

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">
 
 <androidx.recyclerview.widget.RecyclerView
  android:id="@+id/recyclerView"
  android:layout_width="0dp"
  android:layout_height="0dp"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintBottom_toBottomOf="parent">
 </androidx.recyclerview.widget.RecyclerView>
 
</androidx.constraintlayout.widget.ConstraintLayout>

運行一下看一下效果:

運行成功,沒有問題。

最開始說Paging有缺點,其實Paging是沒有下拉刷新的,只有上拉加載更多功能。這個并不滿足很多列表場合。

但是如果只需要上拉加載更多的話,Paging還是推薦使用的,畢竟是Google提供的。

上面代碼親測沒問題,有問題請留言。

代碼地址:https://github.com/LeoLiang23/PagingDemo.git

到此這篇關(guān)于Android Jetpack- Paging的使用詳解的文章就介紹到這了,更多相關(guān)Android Jetpack Paging內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android中post和get的提交方式【三種】

    Android中post和get的提交方式【三種】

    本文主要對Android中三種POST和GET的提交方式進(jìn)行詳細(xì)介紹。通過任何一種方式可以實現(xiàn)的功能是,從安卓手機(jī)端提交數(shù)據(jù)到服務(wù)器端,服務(wù)器端進(jìn)行判斷,并返回相應(yīng)的結(jié)果。三種方式各有利弊,實現(xiàn)效果相同,在實際的使用過程中可以根據(jù)本身的需要進(jìn)行選擇。
    2016-12-12
  • Android Studio如何查看源碼并調(diào)試的方法步驟

    Android Studio如何查看源碼并調(diào)試的方法步驟

    這篇文章主要介紹了Android Studio如何查看源碼并調(diào)試的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • android九宮格可分頁加載控件使用詳解

    android九宮格可分頁加載控件使用詳解

    這篇文章主要介紹了android九宮格可分頁加載控件的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • Android?Choreographer源碼詳細(xì)分析

    Android?Choreographer源碼詳細(xì)分析

    Choreographer的作用主要是配合Vsync,給上層App的渲染提供一個穩(wěn)定的Message處理的時機(jī),也就是Vsync到來的時候,系統(tǒng)通過對Vsync信號周期的調(diào)整,來控制每一幀繪制操作的時機(jī)
    2022-08-08
  • Android?MaterialButton使用實例詳解(告別shape、selector)

    Android?MaterialButton使用實例詳解(告別shape、selector)

    我們平時寫布局,當(dāng)遇到按鈕需要圓角、或者描邊等,通常的方法是新建一個xml文件,在shape標(biāo)簽下寫,然后通過android:background或setBackground(drawable)設(shè)置,這篇文章主要給大家介紹了關(guān)于Android?MaterialButton使用詳解的相關(guān)資料,需要的朋友可以參考下
    2022-09-09
  • Android查看文件夾大小以及刪除文件夾的工具類

    Android查看文件夾大小以及刪除文件夾的工具類

    這篇文章主要介紹了Android查看文件夾大小以及刪除文件夾的工具類,Android計算文件夾大小和刪除目錄,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Android使用gallery和imageSwitch制作可左右循環(huán)滑動的圖片瀏覽器

    Android使用gallery和imageSwitch制作可左右循環(huán)滑動的圖片瀏覽器

    本文主要介紹了android使用gallery和imageSwitch制作可左右循環(huán)滑動的圖片瀏覽器的示例代碼。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-04-04
  • android 設(shè)置控件的顏色字體的方法

    android 設(shè)置控件的顏色字體的方法

    這篇文章介紹了android 設(shè)置控件的顏色字體的方法,有需要的朋友可以參考一下
    2013-09-09
  • Android 基于MediatorLiveData實現(xiàn)紅點的統(tǒng)一管理

    Android 基于MediatorLiveData實現(xiàn)紅點的統(tǒng)一管理

    這篇文章主要介紹了Android 基于MediatorLiveData實現(xiàn)紅點的統(tǒng)一管理,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下
    2021-04-04
  • Android中檢查、設(shè)置默認(rèn)程序詳解

    Android中檢查、設(shè)置默認(rèn)程序詳解

    這篇文章主要介紹了Android中檢查、設(shè)置默認(rèn)程序詳解,本文講解了檢測是否有默認(rèn)的程序、如果有默認(rèn)程序、沒有默認(rèn)的程序的情況等內(nèi)容,需要的朋友可以參考下
    2015-01-01

最新評論