1.Activity管理fragment显示位置,并且通过FragmentManager管理fragment队列及fragment失误回退栈。
public class MainActivity extends FragmentActivity
{
private ContentFragment mContentFragment ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
mContentFragment = (ContentFragment) fm.findFragmentById(R.id.id_fragment_container);
if(mContentFragment == null )
{
mContentFragment = new ContentFragment();
fm.beginTransaction().add(R.id.id_fragment_container,mContentFragment).commit();
}
}
}
2.Fragment Arguments
即Fragment.setArguments(Bundle bundle);
和Bundle bundle = getArguments();
3.创建Fragment方式(降低耦合度)
/**
* 传入需要的参数,设置给arguments
* @param argument
* @return
*/
public static ContentFragment newInstance(String argument)
{
Bundle bundle = new Bundle();
bundle.putString(ARGUMENT, argument);
ContentFragment contentFragment = new ContentFragment();
contentFragment.setArguments(bundle);
return contentFragment;
}
4.Fragment的startActivityForResult。
fragment中可以使用startActivityForResult()和onActivityResult(),没有setResult();
所以我们在使用时应该使用:
getActivity().setResult();
5.抽象FragmentActivity
public abstract class SingleFragmentActivity extends FragmentActivity
{
protected abstract Fragment createFragment();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment =fm.findFragmentById(R.id.id_fragment_container);
if(fragment == null )
{
fragment = createFragment() ;
fm.beginTransaction().add(R.id.id_fragment_container,fragment).commit();
}
}
}
我们的每个FragmentActivity都应该继承该类,实现代码复用。
6.FragmentPagerAdapter与FragmentStatePagerAdapter
7.Fragment间的数据传递
//将要跳转的fragment
CommentFragment commentFragment = new CommentFragment();
//必须设置该参数,否则无法实现数据传递 commentFragment.setTargetFragment(ContentFragment.this, 0);
commentFragment.show(getFragmentManager(), COMMENT_DIALOG);
//新Fragment
private void setResult(int i){
//getTargetFragment()不为空才能调用前一个fragment的方法
if(getTargetFragment() == null)
return;
Intent intent = new Intent();
intent.putExtra(RESPONSE_COMMENT, comments[i]);
//调用前一个fragment的onActivityResult方法
getTargetFragment().onActivityResult(ContentFragment.REQUERT_COMMENT, Activity.RESULT_OK, intent);
}