Fragment基本使用方法
-
fragment生命周期
-
fragment依赖于Activity
-
fragment通过getActivity()获取当前所在的Activity
-
fragment通过FragmentManager的findFragmentById()
或findFragmentByTag()获取fragment
-
fragment与activity多对多关系
//第一步,实例化
AFragment aFragment = new AFragment();
//第二步,添加fragment
getFragmentManager().beginTransaction().add(R.id.frame_container, aFragment).commit();
//或者调用,通常调用这个方法不用commit()
getFragmentManager().beginTransaction().add(R.id.frame_container, aFragment).commitAllowingStateLoss();
//getSupportFragment()与getFragmentManager()区别?
getSupportFragmentManager():
3.0以下,3.0以下没有fragment的api,需要V4包通过此方法间接获取FragmentManager()对象,同时继承FragmentActivity,这样才能获取fragment
getFragmentManager():
3.0以上,有了fragment的api,可直接继承Activity获取fragment对象
//问题点commit()与commitAllowingStateLoss()区别?
commit()需要在onSaveInstanceState()之前调用,如果在之后调用就会出现Can not perform this action after onSaveInstanceState异常的提示
commitAllowingStateLoss()则不会进行onSaveInstanceState()保存前后的判断,则不会出现上面的异常提示
if(bFragment == null){
bFragment = new BFragment();
}
getFragmentManager().beginTransaction().replace(R.id.frame_container, bFragment).commitAllowingStateLoss();
生命周期相关
//getActivity()可能为null情况
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity)context; //可能会导致内存泄漏,不推荐
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//遇到getActivity()为空的情况解决方案可以先进行非空判断
if(getActivity() != null){
//做activity相关操作
}
}
}
//fragment传值的方式
public static AFragment newInstance(String title){
AFragment aFragment = new AFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
//如果fragment被重新创建,setArgument也不会丢失,系统会通过setArgument重新赋值
aFragment.setArguments(bundle);
return aFragment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(getArguments() != null){
getArguments().getString("title"); //获取传入的值
}
}
//将fragment添加到回退栈中,不至于返回时,只返回到Activity
getFragmentManager().beginTransaction()
.add(R.id.frame_container, aFragment).addToBackStack(null).commitAllowingStateLoss();
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (listenerImpl)context; //实现activity对fragment当中监听的接口
} catch (ClassCastException e) {
e.printStackTrace();
}
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn.setOnClickListener(new View.OnClickListener(){
listener.onClick("进行方法的回调"); //在此对onClick方法在Activity中进行回调
});
}
网友评论