最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android Jetpack- Paging的使用詳解

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

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

     Jetpack 的東西也不少,

    

     今天就搞一下這個(gè)  Paging

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

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

    主要流程是:

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

     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,其實(shí)它是繼承了 RecyclerView.Adapter 的,所以用起來(lái)沒(méi)和 RecyclerView.Adapter 多大區(qū)別,就是多了一個(gè)內(nèi)部需要實(shí)現(xiàn) DiffUtil.ItemCallback 來(lái)。具體 DiffUtil.ItemCallback 的原理就不在這說(shuō)了,博主也沒(méi)有細(xì)究,它是用來(lái)比較數(shù)據(jù)的。其內(nèi)部實(shí)現(xiàn)方法也基本上可以寫(xiě)死。

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) {
     // 比較兩個(gè)Item數(shù)據(jù)是否一樣的,可以簡(jiǎn)單用 Bean 的 hashCode來(lái)對(duì)比
     return oldConcert.hashCode() == newConcert.hashCode();
    }
 
    @Override
    public boolean areContentsTheSame(MyDataBean oldConcert,
             MyDataBean newConcert) {
     // 寫(xiě)法基本上都這樣寫(xiě)死即可
     return oldConcert.equals(newConcert);
    }
   };
 
 
 public MyPagedListAdapter() {
  // 通過(guò) 構(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)部方法,通過(guò)此方法可以獲取到對(duì)應(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ù)分頁(yè)請(qǐng)求。

需要實(shí)現(xiàn)兩個(gè)方法:

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

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

class MyDataSource : PositionalDataSource<MyDataBean>() {
 
 /**
  * 第一次打開(kāi)頁(yè)面,需要回調(diào)此方法來(lái)獲取數(shù)據(jù)
  * */
 override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<MyDataBean>) {
  // 獲取網(wǎng)絡(luò)數(shù)據(jù)
  val list = getData(params.requestedStartPosition, params.pageSize)
  /**
   *  這個(gè)方法是返回?cái)?shù)據(jù),讓 綁定ViewModel 感知。 這里要用對(duì)方法
   *  @param1 數(shù)據(jù)列表
   *  @param2 數(shù)據(jù)為起始位置
   *  @param3 數(shù)據(jù)列表總長(zhǎng)度,這個(gè)一定要設(shè)置好哦,如果設(shè)置了50,
   *    當(dāng)列表的長(zhǎng)度為50時(shí),列表再也無(wú)法出發(fā) loadRange() 去加載更多了
   *    如果不知道列表總長(zhǎng)度,可以設(shè)置 Int 的最大值 999999999
   *    這里設(shè)置 10000
   * */
  callback.onResult(list, 0, 10000)
 }
 
 /**
  * 當(dāng)有了初始化數(shù)據(jù)之后,滑動(dòng)的時(shí)候如果需要加載數(shù)據(jù)的話,會(huì)調(diào)用此方法。
  * */
 override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MyDataBean>) {
  /**
   *  params.startPosition 列表需要從 startPosition 加載更多
   *  params.loadSize  列表需要從 startPosition 加載長(zhǎng)度 為 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è)定每一次加載的長(zhǎng)度 
   *    這個(gè)和 PositionalDataSource 回調(diào)方法 loadSize 一致的
   * */ 
  mDataList = LivePagedListBuilder(dataFactory, 20).build()
 }
 
 // 暴露方法,讓Activity 感知數(shù)據(jù)變化,去驅(qū)動(dòng) 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>

運(yùn)行一下看一下效果:

運(yùn)行成功,沒(méi)有問(wèn)題。

最開(kāi)始說(shuō)Paging有缺點(diǎn),其實(shí)Paging是沒(méi)有下拉刷新的,只有上拉加載更多功能。這個(gè)并不滿足很多列表場(chǎng)合。

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

上面代碼親測(cè)沒(méi)問(wèn)題,有問(wèn)題請(qǐng)留言。

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

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

相關(guān)文章

最新評(píng)論

海南省| 搜索| 富宁县| 利辛县| 黎城县| 南京市| 卓资县| 信宜市| 遂溪县| 开化县| 陆河县| 兰西县| 什邡市| 理塘县| 涪陵区| 龙胜| 东丰县| 浮梁县| 浦县| 曲靖市| 德化县| 修水县| 双峰县| 荆州市| 金华市| 宜川县| 大新县| 萍乡市| 广平县| 永川市| 嘉义市| 昭觉县| 吐鲁番市| 莫力| 丹寨县| 辽中县| 莆田市| 北海市| 柳州市| 湖南省| 永和县|