I am using a simple fragment navigation system, which makes it easy to keep instances of fragments on screen rotation.
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = LayoutInflater.from(getContext()).inflate(getLayoutId(), null, false);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final XmlResourceParser parser = getContext().getResources().getLayout(getLayoutId());
try {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
}
} catch (XmlPullParserException | IOException e) {}
final AttributeSet attrs = Xml.asAttributeSet(parser);
view.setLayoutParams(container.generateLayoutParams(attrs));
return view;
}
The fragments use setRetainInstance(true)
and this part of the code should fix the memory leak mentioned here: Further understanding setRetainInstance(true)
Also on the restart of the activity when screen rotates the fragments are stored in bundle and then restored back from the bundle and one fragment is set as visible. Is it correct to load all fragments on app start and keep them in memory or should they be loaded only when required?