tjm1706 tjm1706 - 5 months ago 17
Android Question

Android: strange issues in my app with 1 fragment after device rotation

My app consists of 1 fragment. This fragment contains a recyclerview with a large number of entries.

The symptom was that after device rotation it seemed not possible to scroll the recyclerview to the saved position. Whatever I did, no scrolling was the result. So, strange things happened in the UI.

EDIT (revealing the root cause) ...

In my activity I had this code ...

if (findViewById(R.id.fragment_container) != null) {
FragmentCategoryChecklist f2 = new FragmentCategoryChecklist();
Bundle b = new Bundle();
b.putString("contents", "Category Fragment");
f2.setArguments(b);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, f2).commit();
}


This is wrong! See the below code.

When the device is rotated with this code, this creates each time a new fragment. This is wrong because Android ALREADY recreates the (saved) fragment.

The result of this is that a fragment is created with instance data by the code, then immediately destroyed and then recreated without any instance-data. No saved instance data means no scrolling to a previously saved position.

The correct code is shown below. Sorry, my question was only a symptom and not showing the root cause.

Fragment f = getSupportFragmentManager().findFragmentById( R.id.fragment_container);
if( f == null) {
if (findViewById(R.id.fragment_container) != null) {
FragmentCategoryChecklist f2 = new FragmentCategoryChecklist();
Bundle b = new Bundle();
b.putString("contents", "Category Fragment");
f2.setArguments(b);
getSupportFragmentManager().
beginTransaction().
replace(R.id.fragment_container, f2).
commit();
}
}

Answer

The root cause of the issue is shown after the EDIT part of the question.

The solution of correctly starting fragments after a device rotation is:

Fragment f = getSupportFragmentManager().findFragmentById( R.id.fragment_container);
if( f == null) {
    if (findViewById(R.id.fragment_container) != null) {
        FragmentCategoryChecklist f2 = new FragmentCategoryChecklist();
        Bundle b = new Bundle();
        b.putString("contents", "Category Fragment");
        f2.setArguments(b);    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, f2).commit();
    }
}

This will create a new fragment after device rotation ONLY if it is not existing.

And the oririginal question?

Is solved very simply, just by adding a ...

((LinearLayoutManager) recyclerview.getLayoutManager()).scrollToPositionWithOffset( jumpToCurrentSelection, 20);