Android ViewPager与Fragment联动

Posted 森然献凉i

tags:

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

说明:ViewPager与Fragment联动实现界面切换

由于我们使用的是ViewPager2,所以首先,我们引入ViewPager2依赖

    implementation "androidx.viewpager2:viewpager2:1.0.0"

布局文件很简单

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <androidx.viewpager2.widget.ViewPager2
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:id="@+id/id_viewpager">
  </androidx.viewpager2.widget.ViewPager2>

</LinearLayout>

新建一个适配器

MyFrafgmentPagerAdapter.java
package com.cdw.study7;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

public class MyFrafgmentPagerAdapter  extends FragmentStateAdapter 
    //存储fragmen的集合
    List<Fragment>fragmentList=new ArrayList<>();
    public MyFrafgmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,List<Fragment>fragments) 
        super(fragmentManager, lifecycle);
        //将集合传递进来
        fragmentList=fragments;
    

    @NonNull
    @Override
    public Fragment createFragment(int position) 
        return fragmentList.get(position);
    
    //fragment的个数
    @Override
    public int getItemCount() 
        return fragmentList.size();
    

新建一个空白fragment,修改布局文件

fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment">

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

</FrameLayout>

修改java文件

BlankFragment.java
package com.cdw.study7;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

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

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


    // TODO: Rename and change types of parameters
    private String mtextString;
    View rootview;


    public BlankFragment() 
        // Required empty public constructor
    

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1) 
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        //param1赋值到ARG_TEXT
        args.putString(ARG_TEXT, param1);

        fragment.setArguments(args);
        return fragment;
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            mtextString = getArguments().getString(ARG_TEXT);

        
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        //避免重复解析,源浪费
        if (rootview == null) 
            //解析xml
           rootview= inflater.inflate(R.layout.fragment_blank, container, false);
        
        initview();
        return rootview;
    

    private void initview() 
        TextView textView=rootview.findViewById(R.id.text);
        textView.setText(mtextString);
    

MainActivity.java

package com.cdw.study7;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 
    ViewPager2 viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPage();
    
    private void initPage()
        viewPager=findViewById(R.id.id_viewpager);
        //创建Fragment
        ArrayList<Fragment>fragments=new ArrayList<>();
        fragments.add(BlankFragment.newInstance("微信聊天"));
        fragments.add(BlankFragment.newInstance("通讯录"));
        fragments.add(BlankFragment.newInstance("发现"));
        fragments.add(BlankFragment.newInstance("我"));
        MyFrafgmentPagerAdapter pagerAdapter=new MyFrafgmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
        //加载适配器
        viewPager.setAdapter(pagerAdapter);
    

效果图

当我向右滑动

后续滑动同上效果

结束

以上是关于Android ViewPager与Fragment联动的主要内容,如果未能解决你的问题,请参考以下文章

Fragment嵌套ViewPager切换后数据消失ViewPager空白问题

删除 viewPager2 中的片段使用 FragmentStateAdapter,但仍显示

android viewpager滑动与slidingpanelayout冲突怎么解决

Android ViewPager与Fragment联动

Android 联合ViewPager 与 Fragment

如何在同一页面上的 Fragment 内创建具有 3 个 Fragment 的 ViewPager?