Android Fragment的增加,删除,添加

1.增加:

FragmentManager fgManager = getFragmentManager(); 

 //Activity用来管理它包含的Frament,通过getFramentManager()获取

FragmentTransaction fragmentTransaction = fgManager.beginTransaction();

//获取Framgent事务

fragmentTransaction.add(R.id.fragment, new MyFragment());

//添加  R.id.fragment,指Activity布局中的的id;MyFragment()指继承Fragment先创建的

//指定动画,可以自己添加

//如果需要,添加到back栈中

fragmentTransaction.commit();

//提交事务


2.删除


FragmentManager fgManager = getFragmentManager(); 

 //Activity用来管理它包含的Frament,通过getFramentManager()获取

FragmentTransaction fragmentTransaction = fgManager.beginTransaction();

//获取Framgent事务

Fragment fragment = fgManager.findFragmentById(R.id.fragment);

//删除一个Fragment之前,先通过FragmentManager的findFragmemtById(),找到对应的Fragment

fragmentTransaction.remove(fragment);

//删除获取到的Fragment

//指定动画,可以自己添加

String tag = null;

fragmentTransaction.addToBackStack(tag);

//如果需要,添加到back栈中

fragmentTransaction.commit();

//提交事务


3.替换


FragmentManager fgManager = getFragmentManager(); 

 //Activity用来管理它包含的Frament,通过getFramentManager()获取

FragmentTransaction fragmentTransaction = fgManager.beginTransaction();

//获取Framgent事务

fragmentTransaction.replace(R.id.fragment, new NewFragment());

//其实替换就是先调用remove()方法,之后再掉用add();

//指定动画,可以自己添加

//如果需要,添加到back栈中

fragmentTransaction.commit();

//提交事务


添加动画有两种:

第一种:fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

众多默认动画中的一个;

第二种:fragmentTransaction.setCustomAnimation(R.animator.slide_in_left,R.animator.slide_out_right);

添加自定义动画,第一个xml是通过事务添加到布局的Fragment,而另一个xml是被删除的Fragment;


你可能感兴趣的:(Android开发)