使用 Recycler 视图在片段中实现 Viewpager2

Implementing Viewpager2 in a fragment with Recycler view

我正在尝试在片段中实现 viewpager2,该片段显示带有 Recycler View 的笔记列表。我尝试了不同的解决方案,但我无法弄明白。

这是我的 fragment_notes_list.xml :

<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/notes_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

list_item_notes.xml用于显示recycler view viewholder:

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_pertanyaan"
    android:layout_width="match_parent"
    android:layout_height="96dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="12dp"
    android:layout_marginRight="16dp"
    android:clickable="true"
    android:foreground="?selectableItemBackground"
    card_view:cardBackgroundColor="#595959"
    card_view:cardCornerRadius="8dp"
    card_view:contentPadding="10dp">

    <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:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/notes_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="8dp"
            android:text="Title"
            android:textColor="@color/white"
            app:layout_constraintBottom_toTopOf="@+id/notes_body"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_chainStyle="packed" />

        <TextView
            android:id="@+id/notes_body"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/notes_title" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

来自片段 class NotesListFragment.kt 的相关片段:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_notes_list, container, false)

        notesRecyclerView =
            view.findViewById(R.id.notes_recycler_view) as RecyclerView
        registerForContextMenu(notesRecyclerView)
        notesRecyclerView.layoutManager = LinearLayoutManager(context)
        notesRecyclerView.adapter = adapter
        return view
    }

private inner class ScreenSlidePagerAdapter(fa: Fragment) : FragmentStateAdapter(fa) {

        override fun getItemCount(): Int = NUM_PAGES

        override fun createFragment(position: Int): Fragment {
            return if (position == 0) {
                NotesListFragment()
       

 } else {
            CalenderFragment()
        }
    }
}



override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        notesListViewModel.notesListLiveData.observe(
            viewLifecycleOwner,
            Observer { notes ->
                notes?.let {
                    Log.i(TAG, "got notes")
                    updateUI(notes)
                }
            })
    }

private inner class NotesAdapter(var notes: List<Notes>) : RecyclerView.Adapter<NotesHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesHolder {
            val view = layoutInflater.inflate(R.layout.list_item_notes, parent, false)

           /* viewPager = view.findViewById(R.id.pager)

            val pagerAdapter = ScreenSlidePagerAdapter(this@NotesListFragment)
            viewPager.adapter = pagerAdapter */

            return NotesHolder(view)
        }

        override fun getItemCount() = notes.size

        override fun onBindViewHolder(holder: NotesHolder, position: Int) {
            val note = notes[position]
            holder.bind(note)
     



 }
    }

我很困惑是否应该在 list_item_notes.xml 中添加 ViewPager2 和 FrameLayout? 但是我该如何为它实现 ScreenSliderPagerAdapter 呢?

我假设您想要 2 个片段:列表和日历,这就是您需要实现 ViewPager2 的原因。您的 NotesListFragment 看起来不错。你有 recyclerview 那里有注释,但你现在想要的是提供 NotesListFragment 和 CalendarFragment 的列表,它们可以在 left/right 方向滚动。首先,在片段代码之外提取 ScreenSlidePagerAdapter。接下来,您必须将 ViewPager2 添加到 parent activity/fragment

<androidx.viewpager2.widget.ViewPager2
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

然后在您的 parent activity/fragment 中像这样将它与适配器配对:

val viewPager = findViewById(R.id.pager)
val pagerAdapter = ScreenSlidePagerAdapter(this)
viewPager.adapter = pagerAdapter

您可以在官方文档中阅读更多相关信息:https://developer.android.com/training/animation/screen-slide-2

我之前也曾尝试在 Main Activity 中实现 ViewPager。但是这样我就无法关闭 viewpager 片段,因为它们始终可见。我该如何解决这个问题?

这是我的主要 activity 在您建议的更改之后:

class MainActivity : AppCompatActivity(),
NotesListFragment.Callbacks {
    private lateinit var viewPager: ViewPager2

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

        viewPager = findViewById(R.id.pager)
        val pagerAdapter = ScreenSlidePagerAdapter(this)
        viewPager.adapter = pagerAdapter
}

override fun onNotesSelected(notesId: UUID) {
        val fragment = NotesFragment.newInstance(notesId)
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .addToBackStack(null)
            .commit()
    }

    fun onNotesDeleted(notes: Notes) {
        val fragment = NotesListFragment()
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
        Toast.makeText(this, "Note Deleted", Toast.LENGTH_SHORT).show()
    }

mainactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pager"/>

</FrameLayout>

这里是一些截图,

https://drive.google.com/drive/folders/13ITZqcaeDeydCe0tW2Iu7VoSGSZnrlkg?usp=sharing

问题解决了。

因为我无法添加带有 NotesListFragment 回收视图的 Viewpager,所以我用 viewpager 制作了另一个父片段并将 NotesListFragment 放入其中。