对 ViewPager 的多选项卡布局使用单个片段 Class

Use Single Fragment Class for Multiple tabs layouts of ViewPager

在 TabsDemoApp 中,我尝试使用一个 Fragment 并在三个 XML 布局之间切换, 我看到这些问题

"How to know which tab is active in onCreateView function?"

我试图理解它并将其应用到这个例子中

这是完整的代码

TabLayoutAdapter

package com.example.tabsdemoapp;

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

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

public class TabLayoutAdapter extends FragmentStatePagerAdapter {

    int mNumOfTabs;

    public TabLayoutAdapter(@NonNull FragmentManager fm, int mNumOfTabs) {
        super(fm, mNumOfTabs);
        this.mNumOfTabs = mNumOfTabs;
    }


    @NonNull
    @Override
    public Fragment getItem(int position) {
        return TabFragment.newInstance(position);
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

TabFragment

package com.example.tabsdemoapp;

import android.content.Context;
import android.os.Bundle;
import android.provider.SyncStateContract;
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;

public class TabFragment extends Fragment {

    private static String ARG_POSITION = "position";
    private static int fragmentId = 0;

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

        if(container.getId() == R.id.tab1) {
            return inflater.inflate(R.layout.tab1, container, false);
        }else if(container.getId() == R.id.tab2){
            return inflater.inflate(R.layout.tab2, container, false);
        }else {
            return inflater.inflate(R.layout.tab3, container, false);
        }
    }


    public static TabFragment newInstance(int position) {
        TabFragment fragment = new TabFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentId = getArguments().getInt(ARG_POSITION,fragmentId);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        assert getTargetFragment() != null;
        getChildFragmentManager().beginTransaction().
                replace(R.id.container, getTargetFragment()).
                commit();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

main_activity.xml

   <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"
    android:id="@+id/rootView"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/myTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="186dp">

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"
        app:elevation="5dp"
        >

    </androidx.viewpager.widget.ViewPager>

</LinearLayout>

MainActivityClass

    public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;
    TabLayoutAdapter adapter;

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

        tabLayout = findViewById(R.id.myTabLayout);
        viewPager = findViewById(R.id.viewPager);

        tabLayout.setupWithViewPager(viewPager);
        adapter = new TabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        viewPager.setCurrentItem(tab.getPosition());
                        break;
                    case 1:
                        viewPager.setCurrentItem(tab.getPosition());
                        break;
                    case 2:
                        viewPager.setCurrentItem(tab.getPosition());
                        break;
                    default:
                        viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }
}

每个选项卡都有三个 XML,tab1、tab2、tab3

tab1.xml

    <?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/tab1"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab one"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

tab2.xml

    <?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/tab2"
    android:orientation="vertical">

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab two"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

tab3.xml

    <?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:orientation="vertical">

    <TextView
        android:id="@+id/tab3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab three"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

在 运行 应用程序之后我看到一个空白页面,没有 ViewPager 和 TabLayout

  1. 为 TabLayout 制作标题,您的 TabLayoutAdapter 应该覆盖 getPageTitle
    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + position;
    }
  1. 你这里错了container传递给onCreateView总是"@+id/viewPager"
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(container.getId() == R.id.tab1) {
            return inflater.inflate(R.layout.tab1, container, false);
        }else if(container.getId() == R.id.tab2){
            return inflater.inflate(R.layout.tab2, container, false);
        }else {
            return inflater.inflate(R.layout.tab3, container, false);
        }
    }

将此代码更改为

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

        if(fragmentId == 0) {
            return inflater.inflate(R.layout.tab1, container, false);
        }else if(fragmentId == 1){
            return inflater.inflate(R.layout.tab2, container, false);
        }else {
            return inflater.inflate(R.layout.tab3, container, false);
        }
    }
  1. 按总片段而不是 tabLayout.getTabCount() 初始化 TabLayoutAdapter 因为现在 tabLayout 没有 child 选项卡它将是 return 0.
 adapter = new TabLayoutAdapter(getSupportFragmentManager(), 3);