【发布时间】:2018-04-11 22:32:46
【问题描述】:
我正在尝试制作一个快速简单的应用程序来学习活动和片段的生命周期。
这是我的 onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "Activity is created", Toast.LENGTH_SHORT).show();
Log.i("onCreate():","Activity is created");
fm = getSupportFragmentManager();
Button button = (Button) findViewById(R.id.toMainFragment);
button.setOnClickListener(new View.OnClickListener() {
Fragment fragment = fm.findFragmentByTag(MAIN);
@Override
public void onClick(View view) {
if(fragment == null) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content, new MainFragment(), MAIN).addToBackStack(null).commit();
}else{
Toast.makeText(getApplicationContext(), "Fragment already created", Toast.LENGTH_SHORT).show();
Log.i("onCreate():","Fragment Already created");
}
}
});
if (savedInstanceState != null){
Toast.makeText(this, "Activity restored data", Toast.LENGTH_SHORT).show();
Log.i("onCreate():","Activity restored data");
}
}
但是,每次我点击按钮时都会创建一个新片段,即使我设置了标签。
我认为片段会保持活力,但会被替换。为什么会这样?
【问题讨论】:
-
我认为投反对票可能是由于标题模糊,但显然我不能确定。