欢迎光临
我们一直在努力

Android 控件 - ViewPager 的适配器(PagerAdapter、FragmentPagerAdapter、FragmentStatePagerAdapter)

ViewPager 概述

  • ViewPager 是 Android 中实现页面滑动切换的经典组件

  • ViewPager 有如下适配器

  • 适配器说明
    PagerAdapter 用于将任意类型的视图与 ViewPager 绑定,自由度最高
    FragmentPagerAdapter 当页面数量较少,且所有 Fragment 都希望常驻内存、不会被销毁时使用
    FragmentStatePagerAdapter 当页面数量很多,,或者 Fragment 可能动态增删时使用
  • ViewPager2 是 ViewPager 升级版

  • 一、PagerAdapter

    1、Adapter
    • view_pager_item_image.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
    android:id="@+id/iv_image"
    android:layout_width="200dp"
    android:layout_height="200dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    • ImagePagerAdapter.kt

    class ImagePagerAdapter(
    private val context: Context,
    private val images: List<Int>
    ) : PagerAdapter() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int {
    return images.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
    return view === `object`
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val view = inflater.inflate(R.layout.view_pager_item_image, container, false)
    val ivImage = view.findViewById<ImageView>(R.id.iv_image)
    ivImage.setImageResource(images[position])
    container.addView(view)
    return view
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
    super.destroyItem(container, position, `object`)

    container.removeView(`object` as View)
    }
    }

    2、Activity
    • activity_view_pager_test.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPagerTestActivity">

    <androidx.viewpager.widget.ViewPager
    android:id="@+id/vp_content"
    android:layout_width="match_parent"
    android:layout_height="370dp"
    android:background="#f5f5f5"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    • ViewPagerTestActivity.kt

    class ViewPagerTestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()
    setContentView(R.layout.activity_view_pager_test)
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
    insets
    }

    val vpContent = findViewById<ViewPager>(R.id.vp_content)

    vpContent.adapter = ImagePagerAdapter(this, listOf(R.drawable.image1, R.drawable.image2))
    }
    }


    二、FragmentPagerAdapter

    1、Adapter
    • MyFragmentPagerAdapter.kt

    class MyFragmentPagerAdapter(
    fm: FragmentManager,
    private val fragments: List<Fragment>,
    private val titles: List<String>
    ) : FragmentPagerAdapter(fm) {
    override fun getCount(): Int {
    return fragments.size
    }

    override fun getItem(position: Int): Fragment {
    return fragments[position]
    }

    override fun getPageTitle(position: Int): CharSequence? {
    return titles[position]
    }
    }

    2、Fragment
    • fragment_home.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="首页页面"
    android:textSize="24sp" />

    <Button
    android:id="@+id/btn_open"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="打开" />

    </LinearLayout>

    • HomeFragment.kt

    public class HomeFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    Button btnOpen = view.findViewById(R.id.btn_open);

    btnOpen.setOnClickListener(v -> {
    Toast.makeText(getActivity(), "test content", Toast.LENGTH_LONG).show();
    });
    }
    }

    • fragment_discover.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="发现页面"
    android:textSize="24sp" />

    </LinearLayout>

    • DiscoverFragment.kt

    public class DiscoverFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_discover, container, false);
    }
    }

    • fragment_profile.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="个人页面"
    android:textSize="24sp" />

    </LinearLayout>

    • ProfileFragment.kt

    public class ProfileFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile, container, false);
    }
    }

    3、Activity
    • activity_view_pager_test.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPagerTestActivity">

    <androidx.viewpager.widget.ViewPager
    android:id="@+id/vp_content"
    android:layout_width="match_parent"
    android:layout_height="370dp"
    android:background="#f5f5f5"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    • ViewPagerTestActivity.kt

    class ViewPagerTestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()
    setContentView(R.layout.activity_view_pager_test)
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
    insets
    }

    val vpContent = findViewById<ViewPager>(R.id.vp_content)

    vpContent.adapter = MyFragmentPagerAdapter(
    supportFragmentManager,
    listOf(HomeFragment(), DiscoverFragment(), ProfileFragment()),
    listOf("Home", "Discover", "Profile")
    )
    }
    }


    三、FragmentStatePagerAdapter

    1、Adapter
    • NewsStatePagerAdapter.kt

    class NewsStatePagerAdapter(
    fm: FragmentManager,
    private val categories: List<String>
    ) : FragmentStatePagerAdapter(fm) {
    override fun getCount(): Int {
    return categories.size
    }

    override fun getItem(position: Int): Fragment {
    return NewsFragment.newInstance(categories[position])
    }

    override fun getPageTitle(position: Int): CharSequence? {
    return categories[position]
    }
    }

    2、Fragment
    • NewsFragment.kt

    class NewsFragment : Fragment() {
    companion object {
    fun newInstance(category: String): NewsFragment {
    return NewsFragment().apply {
    arguments = Bundle().apply {
    putString("category", category)
    }
    }
    }
    }

    override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {
    return TextView(requireContext()).apply {
    text = arguments?.getString("category") ?: "无"
    textSize = 24f
    gravity = Gravity.CENTER
    }
    }
    }

    3、Activity
    • activity_view_pager_test.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPagerTestActivity">

    <androidx.viewpager.widget.ViewPager
    android:id="@+id/vp_content"
    android:layout_width="match_parent"
    android:layout_height="370dp"
    android:background="#f5f5f5"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    • ViewPagerTestActivity.kt

    class ViewPagerTestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()
    setContentView(R.layout.activity_view_pager_test)
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
    insets
    }

    val vpContent = findViewById<ViewPager>(R.id.vp_content)

    vpContent.adapter = NewsStatePagerAdapter(
    supportFragmentManager,
    listOf("推荐", "热点", "科技", "体育", "娱乐")
    )
    }
    }

    赞(0)
    未经允许不得转载:171主机测评 » Android 控件 - ViewPager 的适配器(PagerAdapter、FragmentPagerAdapter、FragmentStatePagerAdapter)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址