动态从列表中创建Tablayout中的选项卡?

huangapple go评论78阅读模式
英文:

Dynamically create tabs in Tablayout from a list?

问题

我的应用程序根据SharedPreference值创建抽屉子菜单。这些子菜单基本上被称为“兴趣”或类别。我试图将相同的功能移到TabLayout,因为这更加方便,但似乎无法使其工作!

编辑基于建议的新代码。

TabsFragment

public class HomeTabsFragment extends Fragment implements ViewPager.OnPageChangeListener {

    private View view;
    private SectionsPagerAdapterHome homePageAdapter;
    public ViewPager viewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.view = inflater.inflate(R.layout.fragment_articles_tabs, container, false);

        TabLayout tabLayout = view.findViewById(R.id.home_list_tabs);
        viewPager = view.findViewById(R.id.home_list_tabs_container);

        homePageAdapter = new SectionsPagerAdapterHome(getFragmentManager());
        viewPager.setAdapter(homePageAdapter);
        viewPager.setOffscreenPageLimit(tabLayout.getTabCount());
        viewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(viewPager);

        if (SharedPrefernces.getUserInterests() != null) {
            List<String> my_interests = SharedPrefernces.getUserInterests();
            Collections.sort(my_interests, String::compareToIgnoreCase);
            my_interests.add(0, getString(R.string.all_stories));
            for (String interest : my_interests) {
                homePageAdapter.addTabPage(new FeedsFragment(), interest);
            }
        }

        return view;
    }

    // 其余方法略...
}

适配器

public class SectionsPagerAdapterHome extends FragmentPagerAdapter {

    private FragmentManager fragmentManager;
    private ArrayList<String> fragmentTags = new ArrayList<>();
    private ArrayList<String> titles = new ArrayList<>();

    protected SectionsPagerAdapterHome(FragmentManager fm) {
        super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        fragmentManager = fm;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object object = super.instantiateItem(container, position);
        if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            String tag = fragment.getTag();
            fragmentTags.add(position, tag);
        }
        return object;
    }

    public Fragment getFragment(int position) {
        Fragment fragment = null;
        String tag = fragmentTags.get(position);
        if (tag != null) {
            fragment = fragmentManager.findFragmentByTag(tag);
        }
        return fragment;
    }

    @Override
    public Fragment getItem(int position) {
        return FeedsFragment.newInstance();
    }

    public void addTabPage(Fragment fragment, String title) {
        titles.add(title);
        fragmentTags.add(fragment.getTag());
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return fragmentTags.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}

我不确定如何实现这一点,所以需要帮助。

英文:

My app creates drawer submenus from sharedpreference values. These submenus are basically called "interests" or categories. I'm trying to move this same functionality to tablayout since that is much more convenient but can't seem to get it to work!

Edit: New code based on suggestions.

TabsFragment:

public class HomeTabsFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterHome homePageAdapter;
public ViewPager viewPager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view =  inflater.inflate(R.layout.fragment_articles_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.home_list_tabs);
viewPager = view.findViewById(R.id.home_list_tabs_container);
homePageAdapter = new SectionsPagerAdapterHome(getFragmentManager());
viewPager.setAdapter(homePageAdapter);
viewPager.setOffscreenPageLimit(tabLayout.getTabCount());
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
if(SharedPrefernces.getUserInterests()!=null) {
List&lt;String&gt; my_interests = SharedPrefernces.getUserInterests();
Collections.sort(my_interests, String::compareToIgnoreCase);
my_interests.add(0, getString(R.string.all_stories));
for (String interest : my_interests) {
homePageAdapter.addTabPage(new FeedsFragment(), interest);
}
}
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity&#39;s menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Fragment fragment = homePageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}

Adapter:

public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private FragmentManager fragmentManager;
private ArrayList fragmentTags = new ArrayList();
private ArrayList&lt;String&gt; titles = new ArrayList();
protected SectionsPagerAdapterHome(FragmentManager fm) {
super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
fragmentManager = fm;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
fragmentTags.add(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
Object tag = fragmentTags.get(position);
if (tag != null) {
fragment = fragmentManager.findFragmentByTag(String.valueOf(tag));
}
return fragment;
}
@Override
public Fragment getItem(int position) {
return FeedsFragment.newInstance();
}
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
@Override
public int getCount() {
return fragmentTags.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}

I'm not sure how I can achieve this so need help.

答案1

得分: 1

由于您正在使用ViewPagerAdapter,而不是使用tabLayout.addTab(...),您需要在适配器中添加项目。可以像这样操作:

public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
   
   private ArrayList<String> fragmentTags = new ArrayList<>();
   private ArrayList<String> titles = new ArrayList<>();
   
   // 其他部分...
        
   public void addTabPage(Fragment fragment, String title) {
      titles.add(title);
      fragmentTags.add(fragment);
      notifyDataSetChanged();
   }

    @Override
    public int getCount() {
        return fragmentTags.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
        
}

请注意,我对代码中的一些拼写错误进行了修正,并将ArrayList的泛型类型更正为String

英文:

Since you are using a ViewPager with an Adapter instead of using tabLayout.addTab(...) you have to add the item in the adapter.
Something like:

public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private ArrayList fragmentTags = new ArrayList();
private ArrayList&lt;String&gt; titles = new ArrayList();
//.....
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
@Override
public int getCount() {
return fragmentTags.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tables.get(position);
}
}

huangapple
  • 本文由 发表于 2020年8月4日 05:13:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63237029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定