我尝试使用材质设计动态创建标签,标签数量会根据arraylist的大小而变化。我只创建了一个要在所有选项卡下显示的片段类。在Fragment类布局中包含recyclerview。 recyclerview应根据选项卡进行更新。
enter code here
arrayList.add("Greece");
arrayList.add("Germany");
arrayList.add("France");
arrayList1.add("United States");
arrayList1.add("United Kingdom");
arrayList1.add("India");
tabString.add("ONE");
tabString.add("TWO");
for(String st:arrayList)
{
temp.add(st);
}
viewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int scrollposition=0;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
scrollposition=position;
if (positionOffsetPixels==0)
{
Bundle bundle = new Bundle();
bundle.putInt("POSITION",position);
ListFragment listFragment=new ListFragment();
listFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().commit();
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
if (state==viewPager.SCROLL_STATE_IDLE)
{
if(scrollposition==0) {
temp.clear();
for (String st : arrayList1) {
temp.add(st);
Log.v("MainActivity","aaa temp.add() : "+st);
}
ListFragment.adapterClass.notifyDataSetChanged();
}
else
{
temp.clear();
for (String st : arrayList) {
temp.add(st);
Log.v("MainActivity","aaa temp.1add() : "+st);
}
ListFragment.adapterClass.notifyDataSetChanged();
}
}
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
for(String cat: tabString)
{
adapter.addFragment(new ListFragment(), cat);
}
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addFragment(Fragment fragment, String title,int i) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}