简体   繁体   中英

Android handling fragment rotation with RadioButtons onClick methods

I have a application which is something like a test. There are a lots of radio buttons and radio groups.
During rotation I'm saving actual test obejct in onSaveInstanceState(...) and then in onCreateView(...) restoring this object. Everything works perfectly fine there.. After rotation everything is set up OK and works fine.

Sample:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
...
    if(savedInstanceState != null)
            mTest = (Test)savedInstanceState.getSerializable(TEST_SAVED);
        else{
            String userId = "";
            if (getArguments() != null) {
                userId = getArguments().getString(PACIENT_ID);
            }
            mTest = new Test(userId, "...");
        }
...
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable(TEST_SAVED, mTest);
}

I'm handling the radio button onClick directly in XML

<RadioButton
    android:id="@+id/radioButtonOt1Btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_column="8"
    android:onClick="onRadioButtonClicked" // HERE
    android:text="10" />

But.. When I click on any radio button after rotation, everything is set to NULL (loaded TextViews, EditTexts.. and of course my Test object).
So the problem is obviously in XML onClick method where goes something wrong.

Anybody has suggestion what is going on? :-) Thank you

Your Activity and Fragments are recreated when orientation change.

You need to set

android:configChanges="orientation|screenSize" 

in manifest for your activity to avoid recreating your fragment when orientation change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM