Android强化——FragmentManger和Fragment

2022/4/30 6:14:48

本文主要是介绍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();
    }

}

 



这篇关于Android强化——FragmentManger和Fragment的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程