Fragment使用(一)


一、实例化Fragment

RecordFragment mRecordFragment = new RecordFragment();

FragmentTransaction fm1 = getFragmentManager().beginTransaction();

二、装填Fragment的方式

replace = add+remove

fm1.replace(containerViewId, fragment);//containerViewId要装填的区域,fragment要装填的碎片

fm1.add(containerViewId, fragment);//同上

fm1.remove(fragment);//fragment要移除的碎片

三、切换Fragment的方式

1.不保留原状:fm1.replace()

每次切换fragment时

A都会执行onPause()—>onStop()—>onDestroyView()—>onDestroy()—>onDetach();

B会在A执行之前执行onCreate()—>onCreateView()—>onActivityCreate()—>onStart()—>onResume();

可以用Scrollview验证,把控件划出屏幕外,点击另一个碎片,再点击回来,发现之前的控件回到初始位置了。

2.保留原状,不重载UI

方式一:在Activity中使用fm1.hide()和fm1.show()的结合

缺点:麻烦,代码量大

if (!mRecordFragment.isAdded()) {//碎片A是否存在,第一次切换到A的时候会执行
fm1.add(R.id.rl_fragment, mRecordFragment);//不存在则添加一个

}
if (mRecordFragment.isHidden()) {//碎片A是否处于隐藏状态,在别的碎片切换到碎片A 时会执行
fm1.show(mRecordFragment);
}
if (mChatFragment.isAdded()) {//隐藏其他碎片
fm1.hide(mChatFragment);
}
if (mContactsFragment.isAdded()) {//隐藏其他碎片
fm1.hide(mContactsFragment);
}
if (mmeFragment.isAdded()) {//隐藏其他碎片
fm1.hide(mmeFragment);
}

由于碎片只是隐藏了,所以不会调用生命周期中的任何方法,被隐藏的碎片依然是存在并且活动的

方式二:在fragment中判断view是否加载过

private View mContainerView ;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mContainerView == null) {
mContainerView = inflater.inflate(R.layout.fragment_answer,
container, false);
initUI();
initData();
initListener();
}
// 避免重复插入同一个View
ViewGroup parent = (ViewGroup) mContainerView.getParent();
if (parent != null) {
parent.removeView(mContainerView);
}
return mContainerView;
}

由于依然是用replace()进行切换,所以活动的碎片只有一个,碎片会按照生命周期来执行,但是不会重载UI

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值