0

in my fragment, my button changes it's visibility to GONE whenever I click on it. I want the visibility to remain GONE when i rotate my screen. I am using onSaveInstanceState but I would like help on what to add in for the outState.

Any help would be greatly appreciated, thanks!

public class PlaylistsFragment extends Fragment {

    private Button add1;



    @Nullable
    @Override

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_playlists, container, false);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.
    }


    @Override
    public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
        final Button add1 = (Button) getView().findViewById(R.id.p_add1);

        add1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add1.setVisibility(View.GONE);

            }
        });
    }
}
Samuel
  • 11
  • 4
  • You might want to use an boolean, then you just check if is true change the visibility to visible, change to GONE otherwise – Shermano Jul 24 '19 at 14:38
  • [Possible duplicate on how to use onSaveInstance](https://stackoverflow.com/questions/16769654/how-to-use-onsaveinstancestate-and-onrestoreinstancestate) – Taseer Jul 24 '19 at 16:14

1 Answers1

0

Try this:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  savedInstanceState.putInt("button_visibility", add1.getVisibility());
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
 myButtonVisibility = savedInstanceState.getInt("button_visibility", 0);
}

For instance in onCreate:

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

    add1 = (Button)findViewById(R.id.p_add1);

    if (savedInstanceState != null) {
        int buttonVisibility = savedInstanceState.getInt("button_visibility", 0);
        // here will IDE complaint about setting only integer
        add1.setVisibility(buttonVisibility == View.VISIBLE ? View.VISIBLE : View.GONE)
    }
}

If you have more question you should definitely check out this tutorial: saveInstanceState tutorial

Enjoy.

Kebab Krabby
  • 1,574
  • 13
  • 21
  • I made an edit see if it's reflected you accidentally passed boolean in setVisibility which can be fixed as 'add1.setVisibility(isAddButtonVisible? View.VISIBLE: View.GONE)' – Bali Jul 24 '19 at 16:01