如果我在这方面有任何错误,请纠正我。这是一个澄清问题,因为我没有看到它在任何地方明确写过。
在 Android 4 中,您可以调用setRetainInstance(true)
aFragment
以便在配置更改(这基本上意味着设备旋转)时,Fragment
不会破坏 java 对象并且不会创建它的新实例。即,保留实例。
这比在 Android 1-3 中更加理智且不那么令人恼火,因为您不必处理和捆绑所有数据,因此可以将其传递给新的(或)实例,然后再次解除捆绑。这基本上是您期望发生的事情,并且可以说它应该如何从一开始就为 s 工作。onRetainNonConfiguration
State
Instance()
Fragment
Activity
Activity
正如您所期望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;
}
}