How to convert a List<Object> to PagedList<Object> and vice-versa?

后端 未结 3 1023
梦谈多话
梦谈多话 2021-02-12 07:08

PagedList is used for Android\'s cool paging library. To make the question as minimal as possible : If i have a list of strings like

          


        
      
      
      
3条回答
  •  终归单人心
    2021-02-12 07:47

    I have converted a List to PagedList by this code in kotlin i think this code can help you

    1. build config

      private val config = PagedList.Config.Builder()
              .setEnablePlaceholders(false)
              .setPageSize(LIST_SIZE)
              .build()
      

    2.create these classes for convert and return my PagedList

         class ListDataSource(private val items: List) : PositionalDataSource() {
                override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback) {
                    callback.onResult(items, 0, items.size)
        }
    
                override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback) {
                    val start = params.startPosition
                    val end = params.startPosition + params.loadSize
                    callback.onResult(items.subList(start, end))
        }
    }
    
            // UiThreadExecutor implementation example
           class UiThreadExecutor : Executor {
                private val handler = Handler(Looper.getMainLooper())
                override fun execute(command: Runnable) {
                   handler.post(command)
        }
    }
    
    1. Pass val myList: List by config and get PagedList

      val pagedList = PagedList.Builder(ListDataSource(myList), config)
                                  .setNotifyExecutor(UiThreadExecutor())
                                  .setFetchExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
                                  .build()
      

      提交回复
      热议问题