FloatingActionButton is visible when calling getVisibility in onResume although it should not

18 views Asked by At

I have the following situation.

I have a FloatingActionButton which is not visible. When I put the App into background by minimizing it, onStop is called. When I bring it back my onResume method suddenly says it is visible, and I do not know why.

Here are my methods:

@Override
protected void onStop() {
    super.onStop();
    int isVisible = fabStopRecording.getVisibility();
    if(isVisible==0) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("StopButtonIsVisible", true);
        this.getIntent().putExtras(bundle);
    }
}

@Override
protected void onResume() {
    super.onResume();
    loadSharedPreferences();
    //retrieving Bundle when returning
    if (this.getIntent().getExtras() != null) {
        Bundle bundle = this.getIntent().getExtras();
        boolean isStopButtonVisible = bundle.getBoolean("StopButtonIsVisible");
        if(isStopButtonVisible) {
            fabStopRecording.setVisibility(View.VISIBLE);
        }
    }
    //redraw Google Map, calling GoogleMap will fail due to NPE
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

In my layout the FloatingActionButton is set to android:visibility="invisible".

Maybe somebody can tell me what I am doing wrong here!

Thank you very much in advance

1

There are 1 answers

0
Bernd On

As always I found the problem after having already asked for help :)

I have implemented the methods onSaveInstanceState and onRestoreInstanceState, too and they are called when bringing the App into background and bringing it into the foreground again. I was not aware of that.

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean("StopButtonIsVisible", true);
    getIntent().putExtras(outState);
}

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null) {
        boolean isStopButtonVisible = savedInstanceState.getBoolean("StopButtonIsVisible", false);
        if (isStopButtonVisible) {
            fabStopRecording.setVisibility(View.VISIBLE);
            fabPauseRecording.setVisibility(View.VISIBLE);
            fabStartRecording.setVisibility(View.INVISIBLE);
        }
    }
}