导航抽屉 - ViewPager未加载正确的片段

时间:2016-05-14 15:38:52

标签: java android android-viewpager navigation-drawer android-tablayout

概述: 我有导航抽屉,其中我有3个部分。他们每个人用3个ViewPagers开始不同的TabLayout。例如,Section Restaurants& Bars将启动TabLayout,其中包含餐馆,咖啡馆和酒吧标签,如果我选择其中一个,则片段将以Key开头,以便它知道要加载哪个RecyclerView。单击每个选项卡将显示包含不同项目的RecyclerView。

问题: 当选择一个部分时,它会使用特定的RecyclerView项目启动第一个选项卡,一切正常。问题是当我滑动到TabLayout中的其他选项卡时。他们不显示他们的项目。当我返回第一个标签时,它也不起作用。但在我看来,RecyclerView项目将显示在中间选项卡上,当我滑过选项卡时,它们会重新加载到我滑动到的选项卡上。

问题: 如何更改代码,以便当我单击/滑动到特定选项卡时,它将正确加载它的信息?

奖金问题: 由于TabLayout的第一个选项卡在我启动特定部分时没有加载我做了一个变通方法。我从导航抽屉的onNavigationItemSelected启动第一个选项卡的片段(当我加载一个Section时)。这是一种正确的方法吗?还是有更好的方法?但以太方式我想保持简单:)

这里有一个类似的问题Android ViewPager Loading incorrect fragments,但我不知道如何针对我的情况实施答案。

这是MainActivity

    public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public static final String EXTRA_TAB_TO_LAUNCH = "com.example.georgi.test.Tab_To_Launch";


private ViewPager viewPager;
private TabLayout tabLayout;
public enum SectionToLaunch{ RESTAURANTS, SIGHTSEEING, SPORT }
public enum TabLayoutToLaunch{ RESTAURANTS, CAFES, BARS, MUSEUMS, MONUMENTS, OTHERSIGHTSEEING, OUTDOOR, FITNESS, OTHERSPORT }

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

    viewPager = (ViewPager) findViewById(R.id.tabanim_viewpager);
    tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);

    // Set initial tabBar layout
    setupViewPager(viewPager, SectionToLaunch.SIGHTSEEING);
    sectionSelected(SectionToLaunch.SIGHTSEEING);


    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.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.getMenu().getItem(0).setChecked(true);
    navigationView.setNavigationItemSelectedListener(this);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    // First nav menu
    if (id == R.id.nav_sightseeing) {

        setupViewPager(viewPager, SectionToLaunch.SIGHTSEEING);
        sectionSelected(SectionToLaunch.SIGHTSEEING);
        loadTabLayout(TabLayoutToLaunch.MUSEUMS);

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

        setupViewPager(viewPager, SectionToLaunch.RESTAURANTS);
        sectionSelected(SectionToLaunch.RESTAURANTS);
        loadTabLayout(TabLayoutToLaunch.RESTAURANTS);

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

        setupViewPager(viewPager, SectionToLaunch.SPORT);
        sectionSelected(SectionToLaunch.SPORT);
        loadTabLayout(TabLayoutToLaunch.OUTDOOR);

    } // Second nav menu
      else if (id == R.id.nav_share) {

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

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if(drawer != null)
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void sectionSelected(final SectionToLaunch sectionToLaunch) {
    if(tabLayout != null) {
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());

                if(sectionToLaunch == SectionToLaunch.RESTAURANTS) {
                    switch (tab.getPosition()) {
                        case 0:
                            loadTabLayout(TabLayoutToLaunch.RESTAURANTS);
                            break;
                        case 1:
                            loadTabLayout(TabLayoutToLaunch.CAFES);
                            break;
                        case 2:
                            loadTabLayout(TabLayoutToLaunch.BARS);
                            break;
                    }
                } else if (sectionToLaunch == SectionToLaunch.SIGHTSEEING) {
                    switch (tab.getPosition()) {
                        case 0:
                            loadTabLayout(TabLayoutToLaunch.MUSEUMS);
                            break;
                        case 1:
                            loadTabLayout(TabLayoutToLaunch.MONUMENTS);
                            break;
                        case 2:
                            loadTabLayout(TabLayoutToLaunch.OTHERSIGHTSEEING);
                            break;
                    }
                } else if (sectionToLaunch == SectionToLaunch.SPORT) {
                    switch (tab.getPosition()) {
                        case 0:
                            loadTabLayout(TabLayoutToLaunch.OUTDOOR);
                            break;
                        case 1:
                            loadTabLayout(TabLayoutToLaunch.FITNESS);
                            break;
                        case 2:
                            loadTabLayout(TabLayoutToLaunch.OTHERSPORT);
                            break;
                    }
                }

            }

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

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

private void loadTabLayout(TabLayoutToLaunch tabLayoutToLaunch) {

    MainFragmentList mainFragmentList = new MainFragmentList();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_TAB_TO_LAUNCH, tabLayoutToLaunch);
    mainFragmentList.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_main, mainFragmentList).commit();
}

private void setupViewPager(ViewPager viewPager, SectionToLaunch sectionToLaunch) {

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

    if (sectionToLaunch ==  SectionToLaunch.SIGHTSEEING) {
        adapter.addFrag(new MainFragmentList(), "Museums");
        adapter.addFrag(new MainFragmentList(), "Monuments");
        adapter.addFrag(new MainFragmentList(), "Other");
    } else if (sectionToLaunch ==  SectionToLaunch.RESTAURANTS) {
        adapter.addFrag(new MainFragmentList(), "Restaurants");
        adapter.addFrag(new MainFragmentList(), "Cafes");
        adapter.addFrag(new MainFragmentList(), "Bars");
    } else if (sectionToLaunch ==  SectionToLaunch.SPORT) {
        adapter.addFrag(new MainFragmentList(), "Outdoor Activities");
        adapter.addFrag(new MainFragmentList(), "Fitness");
        adapter.addFrag(new MainFragmentList(), "Other");
    }

    viewPager.setAdapter(adapter);
}
}

这是ViewPagerAdapter

public class ViewPagerAdapter extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}
@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}
@Override
public int getCount() {
    return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}
}

这是碎片     公共类MainFragmentList扩展Fragment {

private List<ClassRestaurants> restaurantsList;
private List<ClassSightseeing> sightseeingList;
private List<ClassSport> sportList;
private RecyclerView recyclerView;
private RecyclerViewAdapterRestaurants adapterRestaurants;
private RecyclerViewAdapterSightseeing adapterSightseeing;
private RecyclerViewAdapterSport adapterSport;
public LinearLayoutManager linearLayoutManager;


public MainFragmentList() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
}



@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view);

    // Initialize layoutManager and assign it to the recyclerView
    linearLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(linearLayoutManager);


    Bundle bundle = this.getArguments();
    if(bundle != null) {

        MainActivity.TabLayoutToLaunch tabToLaunch = (MainActivity.TabLayoutToLaunch) bundle.getSerializable(MainActivity.EXTRA_TAB_TO_LAUNCH);

        if(tabToLaunch != null) {
            switch (tabToLaunch) {
                case RESTAURANTS:

                    setRestaurantsList(MainActivity.TabLayoutToLaunch.RESTAURANTS);
                    // Initialize the recyclerView and set size to be fixed
                    adapterRestaurants = new RecyclerViewAdapterRestaurants(restaurantsList, this, getContext());
                    recyclerView.setHasFixedSize(true);

                    // Initialize the custom recyclerViewAdapter and set it to the recyclerView
                    recyclerView.setAdapter(adapterRestaurants);

                    break;
                case CAFES:

                    setRestaurantsList(MainActivity.TabLayoutToLaunch.CAFES);
                    // Initialize the recyclerView and set size to be fixed
                    adapterRestaurants = new RecyclerViewAdapterRestaurants(restaurantsList, this, getContext());
                    recyclerView.setHasFixedSize(true);

                    // Initialize the custom recyclerViewAdapter and set it to the recyclerView
                    recyclerView.setAdapter(adapterRestaurants);

                    break;
                case BARS:

                    setRestaurantsList(MainActivity.TabLayoutToLaunch.BARS);
                    // Initialize the recyclerView and set size to be fixed
                    adapterRestaurants = new RecyclerViewAdapterRestaurants(restaurantsList, this, getContext());
                    recyclerView.setHasFixedSize(true);

                    // Initialize the custom recyclerViewAdapter and set it to the recyclerView
                    recyclerView.setAdapter(adapterRestaurants);

                    break;
                case MUSEUMS:

                    break;
                case MONUMENTS:

                    break;
                case OTHERSIGHTSEEING:

                    break;
                case OUTDOOR:

                    break;
                case FITNESS:

                    break;
                case OTHERSPORT:

                    break;
            }
        }
    }

}


private void setRestaurantsList(MainActivity.TabLayoutToLaunch tabLayoutToLaunch) {
    restaurantsList = new ArrayList<>();

    switch (tabLayoutToLaunch) {
        case RESTAURANTS:
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.RESTAURANTS, "Godzila", "+359 87 754 4244", R.drawable.restaurants_godzila, "http://www.godzila.bg/", 8, "08:00-23:00", 43.218702, 27.898289));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.RESTAURANTS, "La Pastaria", "+359 89 793 8733", R.drawable.restaurants_lapastaria, "http://www.lapastaria.net/", 10, "08:00-22:00", 43.215322, 27.954675));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.RESTAURANTS, "Bohemi", "+359 89 691 3793", R.drawable.restaurants_bohemi, "http://varna.zavedenia.com/1418/Mehana.BOHEMI/", 7, "19:00-02:00", 43.218950, 27.942706));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.RESTAURANTS, "Happy Center", "+359 70 020 888", R.drawable.restaurants_happy_center, "http://happy.bg/en/our_restaurants.html?restaurant=sevastopol", 10, "09:00-24:00", 43.205606, 27.919930));
            break;
        case CAFES:
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.CAFES, "Graffiti", "+359 88 200 3003", R.drawable.cafes_graffiti ,"https://www.facebook.com/Graffiti-Cafe-184764711556626/", 10, "08:00-24:00", 43.207524, 27.921981));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.CAFES, "Modera", "+359 87 919 8560", R.drawable.cafes_modera ,"https://www.facebook.com/moderahei/info/?tab=overview", 8, "08:00-24:00", 43.220164, 27.914789));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.CAFES, "onyx", "+359 87 919 8560", R.drawable.cafes_onyx,"https://www.facebook.com/pages/onyx-caf%D0%B5-bar/207046512657338?fref=ts", 8, "08:00-03:00", 43.205053, 27.919904));
            break;
        case BARS:
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.BARS, "4as pik", "+359 88 911 0202", R.drawable.bars_chas_pik ,"https://www.facebook.com/4asPikVarna/?fref=ts", 8, "22:30-05:00", 43.205196, 27.926798));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.BARS, "Punta Cana", "+359 89 760 7605 ", R.drawable.bars_punta_cana ,"https://www.facebook.com/%D0%9A%D0%BE%D0%BA%D1%82%D0%B5%D0%B9%D0%BB-%D0%B1%D0%B0%D1%80-PUNTA-CANA-112133025499882/?fref=ts", 8, "20:00-04:00", 43.205344, 27.927214));
            restaurantsList.add(new ClassRestaurants(ClassRestaurants.Category.BARS, "Xtravaganzza", "+359 88 580 0276", R.drawable.bars_xtravaganzza ,"https://www.facebook.com/XtravaganzzaClub/timeline", 9, "22:30-05:00", 43.205445, 27.927847));
            break;
    }
}

0 个答案:

没有答案