15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レイアウトファイルを使用せずに Activity に Fragment を配置する場合の注意

Posted at
final String fragmentClassName = HogeFragment.class.getName();
FragmentManager fm = getSupportFragmentManager(); // or getFragmentManager()
FragmentTransaction ft = fm.beginTransaction();
Fragment f = Fragment.instantiate(this, fragmentClassName, args);
ft.replace(android.R.id.content, f, fragmentClassName);
ft.commit();

このコードでは、デバイスの向きが回転すると Fragement#onActivityCreated() が複数回呼び出され、二回目以降は savedInstanceStatenull になることがある。

これを回避するために FragmentManager#findFragmentByTag() で既に生成済みかどうかチェックし、生成済みであればインスタンスの生成は行わずに FragmentTransaction#attach() でアタッチを行うだけにする。

final String fragmentClassName = HogeFragment.class.getName();
FragmentManager fm = getSupportFragmentManager(); // or getFragmentManager()
Fragment f = fm.findFragmentByTag(fragmentClassName);
FragmentTransaction ft = fm.beginTransaction();
if (null == f)
{
	f = Fragment.instantiate(this, fragmentClassName, args);
	ft.replace(android.R.id.content, f, fragmentClassName);
}
else
{
	ft.attach(f);
}
ft.commit();
15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?