Aayush Taneja
Aayush Taneja

Reputation: 83

onCreateView running twice after recreation of fragment after Orientation Change

I have an Activity containing only a FrameLayout which displays a Fragment. The Fragment only contains a Button.

The working of the app is that the background color of the button changes on clicking the button. The Fragment recieves the color value from an array defined in the MainActivity.

The Activity's code is:

public class MainActivity extends AppCompatActivity {
    frag a;
    FragmentManager fm;
    static int color[] = {Color.RED,Color.BLUE,Color.GREEN};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        a = new frag();
        fm = getFragmentManager();
        FragmentTransaction ft = 
            (fm).beginTransaction().add(R.id.framelayout, a);
        ft.commit();
    }
}

And the Fragment code is:

public class frag extends Fragment implements View.OnClickListener {

    View v;
    Button button;
    int i = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (savedInstanceState!=null) {
            i = (int) savedInstanceState.get("i");
        }

        v = inflater.inflate(R.layout.fragment_frag, container, false);
        button = (Button) v.findViewById(R.id.button);
        button.setBackgroundColor(MainActivity.color[i]);
        button.setOnClickListener(this);
        return v;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("i",i);
    }

    @Override
    public void onClick(View vx) {
        i++;
        if(i%3==0)
            i=0;
        button.setBackgroundColor(MainActivity.color[i]);
    }
}

The problem is that when the screen is rotated and the fragment is recreated, the onCreateView runs twice one after another. The first time, it has a non-null savedInstanceState, but for the second time, the savedInstanceState becomes null (I've observed this using the debugger) . Hence, the color of the button always changes to the RED on re-creation of the fragment, which is the color at the first index of the color Array, and it seems as if the state of the app is not being saved at all.

Why is this happening?

Upvotes: 1

Views: 868

Answers (1)

ono
ono

Reputation: 3102

onCreate in your Activity is called again when you rotate, which means another Fragment will be created and added to your frameLayout. The old one will be recreated, so you have two. Check the savedInstanceState in the Activity onCreate. If it is not null then your Activity was recreated and it is likely that the Fragment is already there. You can also do fragmentManager.findFragmentById(id) and check if it's there before adding it again.

Upvotes: 3

Related Questions