简体   繁体   English

将单个片段 Class 用于 ViewPager 的多个选项卡布局

[英]Use Single Fragment Class for Multiple tabs layouts of ViewPager

In TabsDemoApp I trying to use one Fragment and switch between three XML layouts, I see these questions在 TabsDemoApp 我尝试使用一个片段并在三个 XML 布局之间切换,我看到了这些问题

"How to know which tab is active in onCreateView function?" “如何知道 onCreateView function 中哪个选项卡处于活动状态?”

"Use Single Fragment in Multiple tabs of ViewPager" “在 ViewPager 的多个选项卡中使用单个片段”

I have tried to understand it and apply it to this example我试图理解它并将其应用于此示例

here's the full code这是完整的代码

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

MainActivity Class主要活动 Class

    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) {

            }
        });


    }
}

and there's a three XML for each tab, tab1, tab2, tab3每个选项卡都有三个 XML,tab1,tab2,tab3

tab1.xml 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 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 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>

after running the app I see a blank page, there's no ViewPager and TabLayout运行应用程序后,我看到一个空白页面,没有 ViewPager 和 TabLayout

在此处输入图像描述

  1. Make title for TabLayout, your TabLayoutAdapter should override getPageTitle为 TabLayout 制作标题,您的TabLayoutAdapter应覆盖getPageTitle
    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + position;
    }
  1. You wrong here container pass to onCreateView always is "@+id/viewPager"你在这里错误的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);
        }
    }

Change this code to将此代码更改为

    @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. Init TabLayoutAdapter by total fragments instead of by tabLayout.getTabCount() because now tabLayout doesn't have child tab it will be return 0.通过总片段而不是通过tabLayout.getTabCount()初始化TabLayoutAdapter ,因为现在 tabLayout 没有子选项卡,它将返回 0。
 adapter = new TabLayoutAdapter(getSupportFragmentManager(), 3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM