Android ViewPager2 + Fragment 联动

时间:2022-12-01 07:20:08

本篇主要介绍一下 ViewPager2 + Fragment , 上篇中简单使用了ViewPager2 实现了一个图片的滑动效果, 那图片视图可以滑动, ViewPager2也可以滑动 Fragment

Android ViewPager2 + Fragment 联动

概述

ViewPager2 官方对它的描述就是 以可滑动的格式显示视图或 Fragment 也就说明提供了滑动Fragment的实现 并且还很简单, 下面来看看吧

实现思路

1.Activity 布局文件中引入 ViewPager2 控件
2.编写 Fragment 用于填充到ViewPager2中
3.编写Adapter 实现 FragmentStateAdapter

下面用实际代码 来展示 滑动Fragment

代码实现

Activity 布局文件中引入 ViewPager2 控件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:andro
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ViewPage2FragmentActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:
        android:layout_width="match_parent"
        android:layout_height="300dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@color/pink"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

Android ViewPager2 + Fragment 联动

编写 Fragment 用于填充到ViewPager2中

package com.johnny.slzzing;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ViewPage2Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ViewPage2Fragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public ViewPage2Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ViewPage2Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ViewPage2Fragment newInstance(String param1, String param2) {
        ViewPage2Fragment fragment = new ViewPage2Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_view_page2, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView textView = view.findViewById(R.id.fragmenttextview);
        textView.setText(mParam1);
    }
}
fragment_view_page2
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:andro
    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=".ViewPage2Fragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:gravity="center"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

fragment 很简单 就在中间有个TextView 区分不同的fragment

Android ViewPager2 + Fragment 联动

编写Adapter 实现 FragmentStateAdapter

package com.johnny.slzzing;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import java.util.Arrays;
import java.util.List;

public class ViewPage2FragmentActivity extends AppCompatActivity {

    ViewPager2 viewPage2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_page2_fragment);

        viewPage2 = findViewById(R.id.viewpager2fragment);
        ViewPager2FragmentAdapter viewPager2FragmentAdapter = new ViewPager2FragmentAdapter(this , initFragmentList());
        //重点 ! 把 viewPage2设置adapter 这个adapter 不是去直接继承RecycleView.Adapter了
        viewPage2.setAdapter(viewPager2FragmentAdapter);
    }
    //初始化3个fragment
    private List<Fragment> initFragmentList() {
        ViewPage2Fragment viewPage2Fragment = ViewPage2Fragment.newInstance("我是Fragment1", "");
        ViewPage2Fragment viewPage2Fragment2 = ViewPage2Fragment.newInstance("我是Fragment2", "");
        ViewPage2Fragment viewPage2Fragment3 = ViewPage2Fragment.newInstance("我是Fragment3", "");
        return Arrays.asList(viewPage2Fragment,viewPage2Fragment2,viewPage2Fragment3);
    }

    // 提供了FragmentStateAdapter 只需要继承它即可 不用继承RecycleView.Adapter
    static class ViewPager2FragmentAdapter extends FragmentStateAdapter{

        private final List<Fragment> fragmentList;

        public ViewPager2FragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragmentList) {
            super(fragmentActivity);
            this.fragmentList = fragmentList;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return fragmentList.size();
        }
    }
}

效果

粉色区域是可以滑动切换 不同的Fragment 的

Android ViewPager2 + Fragment 联动

总结

本篇主要介绍了 ViewPager2 结合 Fragment 的基本使用方式 , 让我们可以快速的实现滑动Fragment 的功能. 后续还可以结合 BottomNavigationView 联动 底部导航栏+滑动, 有机会再说把

欢迎大家访问 个人博客 Johnny小屋
欢迎关注个人公众号

Android ViewPager2 + Fragment 联动