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

问题描述 投票:1回答:1

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

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

"Use Single Fragment in Multiple tabs of ViewPager"

我试图理解它并将其应用于此示例

这是完整的代码

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>

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

            }
        });


    }
}

并且每个选项卡(tab1,tab2,tab3)都有三个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

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

enter image description here

android android-fragments android-viewpager android-tablayout android-tabs
1个回答
0
投票
  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. 按总片段而不是按TabLayoutAdapter初始化tabLayout.getTabCount(),因为现在tabLayout没有子选项卡,它将返回0。
 adapter = new TabLayoutAdapter(getSupportFragmentManager(), 3);

© www.soinside.com 2019 - 2024. All rights reserved.