user1972094
user1972094

Reputation: 17

Fragment not added after configuration change

I am trying to recreate view after screen rotation, her I added "TestFragment" to an activity, screen get rotated onConfigurationChange() is called, here I do setcontextview() so that view is recreated and trying to replace existing "TestFragment" with same instance. but fragment is not added, can I know anything wrong in this code.

public class TestFragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Test", "onCreate");
        setContentView(R.layout.activity_test);
        createFragment();
    }

    private void createFragment(){
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("TestFragment");
        if (fragment == null) {
            Log.d("Test", "not found");
            fragment = new TestFragment();

        }else {
            Log.d("Test", "found");
        }
        FragmentTransaction fragmentTransaction;
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frame1, fragment, "TestFragment");
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("Test", "onConfigurationChanged");
        setContentView(R.layout.activity_test);
        createFragment();
    }
}

    public class TestFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.test_fragment, null, false);
        return root;
    }

    @Override
    public void onDestroy() {
        Log.d("Test", "onDestroy TestFragment");
        super.onDestroy();
    }
}

Upvotes: 0

Views: 326

Answers (2)

Prem Chand
Prem Chand

Reputation: 1023

There is no need to call onConfigurationChanged() method if you define android:configChanges="orientation" in Manifest file because Activity will auto manage the current state and content on orientation change.

Upvotes: 0

Cecil Paul
Cecil Paul

Reputation: 643

Add this to your manifest

<activity
        android:name=".TestFragmentActivity"
        android:configChanges="orientation">   
</activity>

Upvotes: 1

Related Questions