markdown Android分页库教程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Android分页库教程相关的知识,希望对你有一定的参考价值。

# Android Paging Library Tutorial
[SOURCE](https://www.raywenderlich.com/6948-paging-library-for-android-with-kotlin-creating-infinite-lists#toc-anchor-001), [SOURCE](https://medium.com/@SaurabhSandav/using-android-paging-library-with-retrofit-fa032cac15f8), [SOURCE](https://blog.iamsuleiman.com/android-pagination-tutorial-swipe-to-refresh/)

### AllClinicalNoteFragment

```
class AllClinicalNoteFragment : BaseLifeCycleFragment<BaseViewModel>() {
    override val viewModelClass: Class<BaseViewModel>
        get() = BaseViewModel::class.java

    companion object {
        fun newInstance(bundle: Bundle?): AllClinicalNoteFragment = AllClinicalNoteFragment().apply { arguments = bundle }
    }

    private val adapter = AllClinicalNoteAdapter()
    private lateinit var dataSource: PageKeyedDataSource<Int, ClinicalNote>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_all_clinical_note, container, false)
    }

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

    private fun initializeList() {
        val patientId = ClinicalNoteBundleBuilder.getPatientId(arguments)

        if (patientId == null) {
            showAlert("Can't display this page. What is missing:\n\n- patientID")
            return
        }

        facc_recycler_view.layoutManager = LinearLayoutManager(context)
        facc_recycler_view.adapter = adapter

        //1
        val config = PagedList.Config.Builder()
                .setInitialLoadSizeHint(20)
                .setPageSize(10)
                .setEnablePlaceholders(true)
                .build()

        //2
        val liveData = initializedPagedListBuilder(config, patientId).build()

        //3
        liveData.observe(this, Observer<PagedList<ClinicalNote>> { pagedList ->
            checkAndHandleEmptyList(pagedList)
            adapter.submitList(pagedList)
            faac_swipe_refresh_layout.isRefreshing = false
        })

        faac_swipe_refresh_layout.setOnRefreshListener { refresh() }
    }

    private fun initializedPagedListBuilder(config: PagedList.Config, patientId: Long): LivePagedListBuilder<Int, ClinicalNote> {
        val dataSourceFactory = object : DataSource.Factory<Int, ClinicalNote>() {
            override fun create(): DataSource<Int, ClinicalNote> {
                dataSource = AllClinicalNoteDataSource(patientId, viewModel)
                return dataSource
            }
        }
        return LivePagedListBuilder<Int, ClinicalNote>(dataSourceFactory, config)
    }

    private fun refresh() {
        dataSource.invalidate()
    }

    private fun checkAndHandleEmptyList(list: List<Any>) {
        if (list.isNullOrEmpty()) {
            faac_no_note_group.visibility = View.VISIBLE
        } else {
            faac_no_note_group.visibility = View.GONE
        }
    }
}
```

### R.layout.fragment_all_clinical_note:

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/faac_swipe_refresh_layout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/facc_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="30dp"
            android:paddingBottom="14dp"
            android:clipToPadding="false" />
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/faac_no_note_iv"
        android:layout_width="80dp"
        android:layout_height="80dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/faac_no_note_tv"
        app:layout_constraintVertical_chainStyle="packed"
        app:srcCompat="@drawable/img_no_clinical_note"/>

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/faac_no_note_tv"
        style="@style/PageHeadline"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        android:layout_marginTop="27dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/faac_no_note_iv"
        app:layout_constraintBottom_toBottomOf="parent"
        android:text="@string/clinical_note_list_no_notes"/>

    <androidx.constraintlayout.widget.Group
        android:id="@+id/faac_no_note_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="faac_no_note_iv,faac_no_note_tv"
        android:visibility="gone"
        tools:visibility="visible"/>
</androidx.constraintlayout.widget.ConstraintLayout>
```

### AllClinicalNoteDataSource

```
class AllClinicalNoteDataSource(val patientId: Long, val viewModel: BaseViewModel) : PageKeyedDataSource<Int, ClinicalNote>() {

    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, ClinicalNote>) {
        viewModel.isLoadingLiveData.postValue(true)
        var offset = 0
        val dis = CommonRepository.instance.getAllClinicalNoteList(patientId, params.requestedLoadSize, offset)
                .subscribe({
                    viewModel.isLoadingLiveData.postValue(false)
                    if (it.isSuccess) {
                        val resultList = it.data.clinicalNotes
                        offset += resultList?.size ?: 0
                        callback.onResult(resultList ?: listOf(), null, offset)
                    } else {
                        viewModel.errorLiveData.postValue(ErrorResponse(ErrorCode.ERR_UNKNOWN, it.message))
                    }
                }, {
                    viewModel.isLoadingLiveData.postValue(false)
                    viewModel.errorLiveData.postValue(ErrorResponse(it))
                })
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, ClinicalNote>) {
        viewModel.isLoadingLiveData.postValue(true)
        val currentOffset = params.key
        val dis = CommonRepository.instance.getAllClinicalNoteList(patientId, params.requestedLoadSize, currentOffset)
                .subscribe({
                    viewModel.isLoadingLiveData.postValue(false)
                    if (it.isSuccess) {
                        val resultList = it.data.clinicalNotes
                        val nextOffset = currentOffset + (resultList?.size ?: 0)
                        callback.onResult(resultList ?: listOf(), nextOffset)
                    } else {
                        viewModel.errorLiveData.postValue(ErrorResponse(ErrorCode.ERR_UNKNOWN, it.message))
                    }
                }, {
                    viewModel.isLoadingLiveData.postValue(false)
                    viewModel.errorLiveData.postValue(ErrorResponse(it))
                })
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, ClinicalNote>) {
        // This is not necessary in our case as our data doesn't change. It's useful in cases where
        // the data changes and we need to fetch our list starting from the middle.
    }
}
```

### AllClinicalNoteAdapter

```
class AllClinicalNoteAdapter : PagedListAdapter<ClinicalNote, AllClinicalNoteViewHolder>(AllClinicalNoteDiffUtilCallback()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AllClinicalNoteViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_item_all_clinical_note, parent, false)
        return AllClinicalNoteViewHolder(view)
    }

    override fun onBindViewHolder(holder: AllClinicalNoteViewHolder, position: Int) {
        val note = getItem(position)
        if (note == null) { // this is the placeholder
            holder.itemView.aiacc_full_name.text = "Loading"
            holder.itemView.aiacc_date.text = "Loading"
            holder.itemView.aiacc_title.text = "Loading"
        } else {
            /*val resources = holder.itemView.context.resources
            val scoreString = resources.getString(R.string.score, item?.score)
            val commentCountString = resources.getString(R.string.comments, item?.commentCount)*/
            holder.itemView.aiacc_image_iv.loadCircleDoctorAvatar(note.imageURL)
            holder.itemView.aiacc_full_name.text = note.fullName
            holder.itemView.aiacc_date.text = note.dateCreated
            holder.itemView.aiacc_title.text = note.title
        }
    }
}
```

### AllClinicalNoteViewHolder

```
class AllClinicalNoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
```

### R.layout.adapter_item_all_clinical_note

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:cardElevation="2dp"
    app:cardCornerRadius="10dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/aiacc_image_iv"
            android:layout_width="40dp"
            android:layout_height="40dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            tools:src="@drawable/bg_circle_1"/>

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/aiacc_start_guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="68dp"/>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/aiacc_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Jan 19, 2019"/>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/aiacc_full_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/BoldTextStyle"
            android:textColor="@color/text_color_dark"
            android:layout_marginEnd="8dp"
            app:layout_constraintStart_toStartOf="@id/aiacc_start_guideline"
            app:layout_constraintEnd_toStartOf="@id/aiacc_date"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/aiacc_title"
            tools:text="Dr. Lam Hieu Long Chuyen Di Bat Trom Bat Cuop Ma Ko Chiu Kham Benh Ne Troi Oi La Troi Dat Oi O La La"/>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/aiacc_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:ellipsize="end"
            app:layout_constraintStart_toStartOf="@id/aiacc_start_guideline"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/aiacc_full_name"
            app:layout_constraintBottom_toBottomOf="parent"
            tools:text="Day la mot cai random content tao lao bi dao nhat he mat troi ne troi oi la troi dat oi"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
```

### AllClinicalNoteDiffUtilCallback

```
class AllClinicalNoteDiffUtilCallback : DiffUtil.ItemCallback<ClinicalNote>() {
    override fun areItemsTheSame(oldItem: ClinicalNote, newItem: ClinicalNote): Boolean {
        return oldItem.clinicalNoteID == newItem.clinicalNoteID
    }

    // this usually the fields that are visually available to user
    override fun areContentsTheSame(oldItem: ClinicalNote, newItem: ClinicalNote): Boolean {
        return oldItem.imageURL == newItem.imageURL &&
                oldItem.fullName == newItem.fullName &&
                oldItem.dateCreated == newItem.dateCreated &&
                oldItem.title == newItem.title
    }
}
```

以上是关于markdown Android分页库教程的主要内容,如果未能解决你的问题,请参考以下文章

分页库过滤器/搜索

具有自定义数据源偏移量的 Android 分页库 RecyclerView 中的项目

使用分页库时,观察者显示列表大小为零

如何使用 codeigniter 分页库回显页码?

使用分页库显示加载指示器

分页库 - 网络 + db 的边界回调,API 获取页面和大小