使用ViewPager将RecyclerView添加到Tabs Fragment

时间:2017-04-21 03:59:23

标签: java android android-fragments android-recyclerview android-viewpager

我有一个带有2个标签的简单片段,我想在每个片段中添加一个recyclerview。我的问题是如何将recyclerview附加到每个片段? 这是我的MainAdapter

public class MainActivity extends AppCompatActivity {
  private List<ListMenu> menuList = new ArrayList<>();
  private RecyclerView recyclerView;
  private MenuAdapter mAdapter;
  @Override        
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("SINGLE"));
    tabLayout.addTab(tabLayout.newTab().setText("PACKET"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final Pageradapter adapter = new Pageradapter(
                     getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(
                    new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    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) {}
      });
  }
}

1 个答案:

答案 0 :(得分:1)

您必须使用FragmentPagerAdapter或PagerAdapter with Fragment

您可以看到示例:

http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

希望!帮助你