ABS Softwares
ABS Softwares

Reputation: 11

How to hide a button after clicked for ever in android?

I want to hide a button when it's clicked for ever.

I tried this code:

playButton.setVisibility(View.GONE);

But when I close and open the app, the button will re-show again .

So how can I hide the button for ever? Thank you :)

Upvotes: 0

Views: 154

Answers (1)

ᴛʜᴇᴘᴀᴛᴇʟ
ᴛʜᴇᴘᴀᴛᴇʟ

Reputation: 4656

You can't technically hide it "forever" but you can do this:

First, declare this variable in your Activity/Fragment:

public static final String SHARED_KEY_BUTTON_HIDE = "my_button_hidden";

Let's say this is your button:

final Button myButton = (Button) findViewById(R.id.button);

Here's the setOnClickListenr for the Button:

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        myButton.setVisibility(View.GONE);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(SHARED_KEY_BUTTON_HIDE, true);
        editor.apply();
    }
});

Here's the key part:

When that Activity start, do this in onCreate() after you declare the button:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean hideButton = preferences.getBoolean(SHARED_KEY_BUTTON_HIDE, false);

if(hideButton) {
    myButton.setVisibility(View.GONE);
}

This will do the job.

Upvotes: 2

Related Questions