以下为本人日常使用Fragment时遇到的一些基础知识点,记录以加深印象:
1. xml layout中静态添加Fragment时,宿主Activity必须继承FragmentActivity
2. 代码中动态加载Fragment时,Fragment显示的区域为layout中的FrameLayout
3.Fragment中根据layout生成UI的代码为:
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_main,container, false);
return view;
}
4. Activity中动态添加Fragment的简单代码为:
getFragmentManager().beginTransaction().replace(R.id.frame_container, mFragment).commit();
5.加载Fragment的时候可以添加动画效果:
getFragmentManager().beginTransaction().setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right).replace(R.id.frame_container, mFragment).commit();
6.Fragment加载其它Fragment时通过getActivity().getSupportFragmentManager()获取FragmentManager对象
7. Activity或者Fragment与其他Fragment传值:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("argument", value);
fragment.setArguments(bundle);
8.单一Fragment被复用时,要保证每次创建的唯一性,同时来回切换时还要避免反复创建,我们可以通过创建它时传递一个tag参数来标记,这样就可以通过tag来获取了:
private void showFragment(int position,String tag)
{
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
Fragment currentFragment = fm.findFragmentById(R.id.frame_container);
Fragment toFragment = fm.findFragmentByTag(tag);
if(toFragment!=null)
{
if(!toFragment.isVisible())
{
transaction.hide(currentFragment);
transaction.show(toFragment);
transaction.commit();
}
}
else
{
transaction.hide(currentFragment);
Fragment fragment = new Fragment();
transaction.add(R.id.frame_container,fragment, tag);
transaction.commit();
}
}
9. Fragment需要创建menu时:
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//清除原先activity的menu
inflater.inflate(R.menu.work, menu);//加载自己的menu
super.onCreateOptionsMenu(menu, inflater);
}