Android Fragment使用记录

出现的问题/疑问以及解决方法

Posted by Kingtous on February 27, 2019

fragment获取systemservice

  • getActivity()获取Activity对象后再操作

获取fragment对象

  • 可以实例化,(然后通过FrameLayout显示fragment)

java.lang.IllegalStateException: Can’t change container ID of fragment

  • fragment动态加载:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private FragmentTransaction switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
         //第一次使用switchFragment()时currentFragment为null,所以要判断一下        
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
         transaction.add(R.id.fragmentShow,targetFragment,targetFragment.getClass().getName());
        } else {
            transaction.hide(currentFragment).show(targetFragment);
        }
        currentFragment = targetFragment;
        return transaction;
    }