Bootstrap

从0开始讲解Fragment和ViewPager2的结合使用(2):混合使用

一.ViewPager2的基本使用

ViewPager2相对于ViewPager1,相当于是对RecyclerView做了一个封装,所以在代码里面会发现很多RecyclerView的身影,而且在ViewPager2的源码中也可以找到RecyclerView变量
在这里插入图片描述

①首先在MainActivity的XML文件中加载ViewPager2

<?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"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myViewPager"
        android:background="@color/purple_500"
        />
        
</LinearLayout>

②然后创建item的布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/container">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/myTextView"
        android:layout_centerInParent="true"
        android:text="这里是TextView"
        android:textColor="@color/black"
        android:textSize="32sp"/>
</RelativeLayout>

③然后设置适配器

public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.MyViewHolder> {
    List<String> items = new ArrayList<>();

    public ViewPagerAdapter() {
        for (int i = 0; i < 10; i++) {
            items.add("我是第"+(i+1)+"个");
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_pager,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.myTextView.setText(items.get(position));
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView myTextView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.myTextView);
        }
    }
}

④然后在MainActivity中进行适配

public class MainActivity extends AppCompatActivity {

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

        ViewPager2 viewPager2 = findViewById(R.id.myViewPager);
        viewPager2.setAdapter(new ViewPagerAdapter());
    }
}

效果
在这里插入图片描述
我们改一下界面背景
⑤首先在Color的资源文件中添加几个颜色
在这里插入图片描述

⑥然后在适配器中做如下更改(我这里只显示了新添的代码)

public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.MyViewHolder> {
    List<Integer> colors = new ArrayList<>();
    ...
    public ViewPagerAdapter() {
		...
        colors.add(R.color.one);
        colors.add(R.color.two);
        colors.add(R.color.three);
        colors.add(R.color.four);
        colors.add(R.color.black);
        colors.add(R.color.one);
        colors.add(R.color.two);
        colors.add(R.color.three);
        colors.add(R.color.four);
        colors.add(R.color.black);
    }
	...
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    	...
        holder.mContainer.setBackgroundResource(colors.get(position));
    }
    ...
    class MyViewHolder extends RecyclerView.ViewHolder {
		...
        RelativeLayout mContainer;
        public MyViewHolder(@NonNull View itemView) {
            ...
            mContainer = itemView.findViewById(R.id.container);
        }
    }
}

效果
在这里插入图片描述
好,经过上面的努力,我们已经掌握了ViewPager2的入门级使用。

二.ViewPager2和Fragment配合使用

下面我们就来将ViewPager2Fragment配合使用
①首先更改MainActivity的xml文件

<?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/myViewPager"
        android:background="@color/purple_500"
        />

</LinearLayout>

②然后创建Fragment

public class BlankFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    String mTextString = "xxx";
    View rootView;

    public static BlankFragment newInstance(String param1) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if(rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_blank, container, false);
        }
        initView();
        return rootView;
    }

    private void initView() {
        TextView textView = rootView.findViewById(R.id.mTextView);
        textView.setText(mTextString);
    }
}

包括其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"
    android:background="@color/white"
    tools:context=".BlankFragment">

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

</FrameLayout>

③然后创建适配器

public class MyAdapter extends FragmentStateAdapter {
    List<Fragment> fragments = new ArrayList<>();
    public MyAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, List<Fragment> fragments) {
        super(fragmentManager, lifecycle);
        this.fragments = fragments;
    }

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

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

④最后在MainActivity中适配数据

public class MainActivity extends AppCompatActivity {
    ViewPager2 viewPager2;

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

        initPage();
    }

    private void initPage() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(BlankFragment.newInstance("我最帅"));
        fragments.add(BlankFragment.newInstance("我最丑"));
        fragments.add(BlankFragment.newInstance("我很帅"));
        fragments.add(BlankFragment.newInstance("我很丑"));

        viewPager2 = findViewById(R.id.myViewPager);
        viewPager2.setAdapter(new MyAdapter(getSupportFragmentManager(),
                getLifecycle(),fragments));
    }
}

运行,就可以看到效果

三.ViewPager和导航栏配合使用

下面看ViewPager和导航栏如何配合使用。
①首先在MainActivity的xml文件中弄一个TabLayout

<?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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/mTabLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.1">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tuesday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Wednesday" />
    </com.google.android.material.tabs.TabLayout>

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

    </androidx.viewpager2.widget.ViewPager2>


</LinearLayout>

默认有3个TabItem
②然后将两者进行联合

public class MainActivity extends AppCompatActivity {
    ViewPager2 viewPager2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPage();
    }

    private void initPage() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(BlankFragment.newInstance("我最帅"));
        fragments.add(BlankFragment.newInstance("我最丑"));
        fragments.add(BlankFragment.newInstance("我很帅"));

        viewPager2 = findViewById(R.id.myViewPager);
        viewPager2.setAdapter(new MyAdapter(getSupportFragmentManager(),
                getLifecycle(),fragments));

        new TabLayoutMediator(findViewById(R.id.mTabLayout),viewPager2,new TabLayoutMediator.TabConfigurationStrategy(){
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position){
                    case 0:
                        tab.setText("1");
                        break;
                    case 1:
                        tab.setText("2");
                        break;
                    case 2:
                        tab.setText("3");
                        break;
                }
            }
        }).attach();
    }
}

关键的就是TabLayoutMediator这个类
使用效果
在这里插入图片描述
OK,我们FragmentViewPager2的配合使用就这样结束啦!

;