【发布时间】:2012-09-11 16:30:44
【问题描述】:
如果我在这方面有任何错误,请纠正我。这是一个澄清问题,因为我没有看到它在任何地方明确写过。
在 Android 4 中,您可以在 Fragment 上调用 setRetainInstance(true),以便在配置更改(这基本上意味着设备轮换)时,Fragment java 对象不会被破坏,并且它的新实例不会创建的。即保留实例。
这比在 Android 1-3 中要理智得多,也不那么令人恼火,因为您不必处理 onRetainNonConfigurationStateInstance() 并将所有数据捆绑起来可以传递给新的Fragment(或Activity)实例,但只能再次解绑。这基本上是您期望发生的事情,并且可以说它应该如何从一开始就为Activitys 工作。
使用setRetainInstance(true),视图也会按照您的预期在旋转时重新创建(调用onCreateView())。我假设(未经测试)资源解析(layout vs layout-land)有效。
所以我的问题有两个:
- 为什么一开始不是
Activities。 - 为什么这不是默认值?您是否有任何理由会真正希望您的
Fragment被无意义地销毁并在轮换时重新创建?因为我想不出来。
编辑
澄清我将如何做到这一点:
class MyFragment extends Fragment
{
// All the data.
String mDataToDisplay;
// etc.
// All the views.
TextView mViewToDisplayItIn;
// etc.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
mDataToDisplay = readFromSomeFileOrWhatever(); // Ignoring threading issues for now.
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
// At this point if mViewToDisplayItIn was not null, the old one will be GC'd.
mViewToDisplayItIn = view.findViewById(R.id.the_text_view);
mViewToDisplayItIn.setText(mDataToDisplay);
}
// Optionally:
@Override
public void onDestroyView()
{
// All the view (and activity) to be GC'd.
mViewToDisplayItIn = null;
}
}
【问题讨论】:
标签: android android-activity rotation fragment lifecycle