-1

How to make the button inactive in sharedpreferences cuz after restart the button becomes active? here is the code to create an inactive button

button.setOnClickListener(new View.OnClickListener() {            
                @Override
                public void onClick(View v) {
                    v.setClickable(false);
                }
            });
Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38

1 Answers1

1
public class MainActivity extends AppCompatActivity {
Button button;
// Initializing SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
static String  IS_DEACTIVE_KEY = "isActive";

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

    // Getting the isDeActive boolean from the sharedpreferences
    Boolean isButtonDeActive = sharedPreferences.getBoolean(IS_DEACTIVE_KEY, false);

    // Checking if we already set button deActive, if so, make it deActive
    if (isButtonDeActive){
        button.setClickable(false);
    }


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setClickable(false);
            // Saving DeActive state true in Sharedpreference
            myEdit.putBoolean(IS_DEACTIVE_KEY,true);
            myEdit.commit();
        }
    });
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 11 '22 at 13:50