其他分享
首页 > 其他分享> > Android强化——FragmentManger和Fragment

Android强化——FragmentManger和Fragment

作者:互联网

Fragment受FragmentManger控制。

通过FragmentManger获取FragmentTransaction。ft.replace(containerView,fragment)替换fragment

 

使用

fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.main_page_container,baseFragment);
        fragmentTransaction.commit();

 

而且fragment内嵌套fragment需要getChildFragmentManger(); 

 

 

public class HomeFragment extends BaseFragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private HomeViewPagerAdapter homeViewPagerAdapter;
    private HomePresenter homePresenter;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView(View view) {
        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.viewPager);
        homeViewPagerAdapter = new HomeViewPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(homeViewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void initPresenter() {
        homePresenter = new HomePresenter();
        homePresenter.setHomeFragment(HomeFragment.this);
    }

    @Override
    public void loadData() {
        homePresenter.getCategories();
    }

    public void loadCategories(Categories categories){
        homeViewPagerAdapter.setCategories(categories);
    }
}

 

HomeViewPagerAdapter

public class HomeViewPagerAdapter extends FragmentPagerAdapter {
    private ArrayList<Categories.Data> dataArray = new ArrayList<>();
    
    public HomeViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        String title = dataArray.get(position).getTitle();
        return title;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        return homePagerFragment;
    }

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

    public void setCategories(Categories categories){
        dataArray.clear();
        List<Categories.Data> data = categories.getData();
        dataArray.addAll(data);
        notifyDataSetChanged();
    }

}

 

标签:FragmentManger,viewPager,void,Fragment,fragment,Override,Android,public,dataArra
来源: https://www.cnblogs.com/remix777/p/16209243.html