Fragment通过hide、show实现动态切换

简单实现XML布局,创建Fragment,找控件,实例化对象,对于大家来说都是小kiss了

Fragment通过hide、show实现动态切换_第1张图片

最核心的代码  showFragment() 

//   展示Fragment
    private void showFragment(Fragment fragment){
        if (currentFragment != fragment){//  判断传入的fragment是不是当前的currentFragmentgit
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.hide(currentFragment);//  不是则隐藏
            currentFragment = fragment;  //  然后将传入的fragment赋值给currentFragment
            if (!fragment.isAdded()){ //  判断传入的fragment是否已经被add()过
                transaction.add(R.id.frameLayout,fragment).show(fragment).commit();
            }else{
                transaction.show(fragment).commit();
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tuijian:
                showFragment(tuijian);
                break;
            case R.id.duanzi:
                showFragment(duanzi);
                break;
            case R.id.video:
                showFragment(video);
                break;
        }
    }


你可能感兴趣的:(Fragment通过hide、show实现动态切换)