简体   繁体   中英

How to save condition of button after closing app?

This is code of button:

 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            button.setEnabled(false);
            new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        button.setEnabled(true);
                    }
                },120000);
            }
        });

I know that i need to create a sharedpreferences, but I didn't understand how to save condition of button which have a timer, because i know how to save without ussing handler. How can i do this?

You'll have to use shared preference to save the state. Then, while creating the view of you fragment or activity, you should check the value you saved with shared preference and set the button state accordingly.

Permit me, please, to answer in Kotlin, maybe you or your IDE can do the translation.

To save your button state to shared preference, define this function;

fun setButtonState(context: Context, buttonEnabled: Boolean) {
    PreferenceManager.getDefaultSharedPreference(context).edit()
        .putBoolean("button", buttonEnabled).apply()
}

Then to get your saved button state from shared preference, define this function;

fun getButtonState(context: Context): Boolean {
    return PreferenceManager.getDefaultSharedPreference(context)
       .getBoolean("button", false)
}

In your onCreateView set the button state in accordance to your saved value.

val buttonEnabled = getButtonState(requireContext())
button = view.findViewById(R.id.button)
button.isEnabled = buttonEnabled

Then toggle the saved state in shared preference like so:

button.setOnClickListener {
     button.isEnabled = false
     setButtonState(requireContext(), false)
     Handler(Looper.getMainLooper()).postDelayed({
         button.isEnabled = true
         setButtonState(requireContext(), true)
     }, 120000)
}

I hope this helps. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM