测试项目
FragmentActivity
public class FragmentActivity extends AppCompatActivity {
private FrameLayout frameLayout;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
frameLayout = findViewById(R.id.fl_content);
button = findViewById(R.id.btn_click);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fTwo = new FragmentOne();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction tx = fm.beginTransaction();
tx.replace(R.id.fl_content, fTwo, "One");
tx.addToBackStack(null);//添加回退栈
tx.commit();
System.out.println("fm.getBackStackEntryCount() = " + fm.getBackStackEntryCount());
}
});
}
}
FragmentOne(FragmentTwo、FragmentThree同理)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View mView = inflater.inflate(R.layout.fragment_one, container, false);
editText = mView.findViewById(R.id.et_input);
button = mView.findViewById(R.id.btn_next);
System.out.println("mView.findViewById = "+editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fTwo = new FragmentTwo();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction tx = fm.beginTransaction();
tx.replace(R.id.fl_content, fTwo, "TWO");
tx.addToBackStack(null);
tx.commit();
System.out.println( "fm.getBackStackEntryCount() = "+ fm.getBackStackEntryCount());
}
});
return mView;
}
@Override
public void onStop() {
super.onStop();
Log.d("Tina======>", "onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d("Tina======>", "onDestroyView"+editText);
}
@Override
public void onDetach() {
super.onDetach();
Log.d("Tina======>", "onDetach");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Tina======>", "onDestroy");
}
前提条件是添加fragmet的时候都是用的replace(先remove 后add)
操作1:
全部添加回退栈的操作
生命周期
开启的时候,打开到第三个fragment
回退的时候
结束.png
操作2:
fragmentOne不加回退栈,其他加
生命周期
开启的时候
回退的时候
结束.png
结论
1.replace 会销毁视图,生命周期走到了onDestroyView
2.加入回退栈,返回的时候,fragment还可以重新显示出来,否则返回的时候,就直接销毁了
3.加入回退栈后,返回时会重新走onCreateView方法,重新绑定视图,也就是说,实例对象会变
举例:recyclerview的话,返回回来后,之前setAdapter就没有了,因为对象换了
注意有一个还会是原来的值,是因为它对数据有保存,他就是edictText(要有id值)
网友评论