Android ViewPager2 + Fragment 联动效果的实现思路

手机APP/开发
379
0
0
2023-06-26
标签   Android
目录
  • Android ViewPager2 + Fragment 联动
  • 概述
  • 实现思路
  • 代码实现
  • 效果
  • 总结

Android ViewPager2 + Fragment 联动

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

概述

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

实现思路

1.Activity 布局文件中引入 ViewPager2 控件

2.编写 Fragment 用于填充到ViewPager2中

3.编写Adapter 实现 FragmentStateAdapter

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

代码实现

Activity 布局文件中引入 ViewPager2 控件

<?xml version=".0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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=".ViewPageFragmentActivity">

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

编写 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 ViewPageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ViewPageFragment extends Fragment {

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

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

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

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam = getArguments().getString(ARG_PARAM1);
            mParam = 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_page, 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(mParam);
    }
}

fragment_view_page2

<?xml version=".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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPageFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/fragmenttextview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:gravity="center"
        android:textSize="sp"
        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

编写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.viewpager.adapter.FragmentStateAdapter;
import androidx.viewpager.widget.ViewPager2;

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

public class ViewPageFragmentActivity extends AppCompatActivity {

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

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

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

        private final List<Fragment> fragmentList;

        public ViewPagerFragmentAdapter(@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 的

总结

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