On navigation item selected not showing fragment with Tab Layout

时间:2016-08-31 17:10:19

标签: java android android-fragments

I am doing a project in which I want to show different fragments depending on where I pick on the navigation view. The problem is that It never shows the fragments that it must show.

The view of the Navigation view is called activity_main and from there you can arrive to the content_main which is the layout used by the fragment manager.

The problem is that the two tabs are not integrated in the toolbar of the mainactivity

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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:fitsSystemWindows="true"
    tools:context="com.blindsiot.carlos.blindsiot.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.blindsiot.carlos.blindsiot.MainActivity"
    tools:showIn="@layout/app_bar_main">

</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    navigationView.setCheckedItem(R.id.nav_principal);

    /* (. . .) */


    @Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    Fragment currFragment = null;
    FragmentManager fragmentManager = getSupportFragmentManager();

    if (id == R.id.nav_principal) {
        currFragment = new FastAccessFragment();
    } else if (id == R.id.nav_planning) {
        currFragment = new SignUp();
    } else if (id == R.id.nav_settings) {

    } else if (id == R.id.nav_help) {

    } else if (id == R.id.nav_logout) {
        editor.putBoolean("signedUp", false);
        editor.apply();
        Intent intent = new Intent(this, LoginActivity.class);
        if (intent != null) {
            this.finish();
            startActivity(intent);
        }
    } else if (id == R.id.nav_about) {

    }

    if (currFragment != null) {
        fragmentManager
                .beginTransaction()
                .replace(R.id.content_main, currFragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit();
    }

    setTitle(item.getTitle());


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

FastAccessFragment.java - This is where I am actually and where I don't understand why It does not work

public class FastAccessFragment extends Fragment {

private ViewPager viewPager;
View rootview;
TabLayout tabLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fast_access_fragment, container, false);
    tabLayout = (TabLayout) rootview.findViewById(R.id.tabLayout_fragment);

    tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.action_sign_in_short)).setIcon(R.drawable.tab_login));
    tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.action_sign_up_short)).setIcon(R.drawable.tab_user));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) rootview.findViewById(R.id.pager_fragment);

    PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(pagerAdapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
            tabLayout.getTabAt(0).setText("test");
            tabLayout.getTabAt(1).setText("test2");
        }
    });

    //Adding onTabSelectedListener to swipe views
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

        }

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

        }
    });

    return rootview;
}

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                SignUp tab1 = new SignUp();
                return tab1;
            case 1:
                SignIn tab2 = new SignIn();
                return tab2;
            default:
                return null;
        }
    }

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

  }

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

我也遇到了同样的问题。我在Home菜单的“导航抽屉活动”中的TabLayout和ViewPager的片段中有一个片段。

当我单击另一个菜单并单击Home时,TabLayout中的片段从未加载。该选项卡已加载,但未加载内容。

花了我近三天的时间才找出原因。最后,我知道我们应该使用getChildFragmentManager()而不是getActivity().getSupportFragmentManager()。因为什么?因为ViewPager放在Fragment中,而不是Activity中。希望它能对遇到相同问题的任何人有所帮助。

这是错误的:

private void setupViewPager(View rootView)
{
    this.mainViewPager = rootView.findViewById(R.id.view_pager_main);

    FragmentManager fragmentManager = this.getActivity().getSupportFragmentManager();

    ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

    DataListFragment movieFragment = (DataListFragment) ((MainActivity) this.getActivity()).getTabFragment(0);
    DataListFragment tvFragment = (DataListFragment) ((MainActivity) this.getActivity()).getTabFragment(1);

    adapter.addFragment(movieFragment);
    adapter.addFragment(tvFragment);

    this.mainViewPager.setAdapter(adapter);
}

这是正确的:

private void setupViewPager(View rootView)
{
    this.mainViewPager = rootView.findViewById(R.id.view_pager_main);

    FragmentManager fragmentManager = this.getChildFragmentManager();

    ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

    DataListFragment movieFragment = (DataListFragment) ((MainActivity) this.getActivity()).getTabFragment(0);
    DataListFragment tvFragment = (DataListFragment) ((MainActivity) this.getActivity()).getTabFragment(1);

    adapter.addFragment(movieFragment);
    adapter.addFragment(tvFragment);

    this.mainViewPager.setAdapter(adapter);
}