简体   繁体   English

关闭应用程序后如何保存按钮的状态?

[英]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.您必须使用共享首选项来保存 state。然后,在创建您的片段或活动的视图时,您应该检查您使用共享首选项保存的值并相应地设置按钮 state。

Permit me, please, to answer in Kotlin, maybe you or your IDE can do the translation.请允许我在 Kotlin 中回答,也许你或你的 IDE 可以做翻译。

To save your button state to shared preference, define this function;要将按钮 state 保存到共享首选项,请定义此 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;然后从共享首选项中获取您保存的按钮 state,定义这个 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.在您的onCreateView中,根据您保存的值设置按钮 state。

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

Then toggle the saved state in shared preference like so:然后在共享首选项中切换保存的 state,如下所示:

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

I hope this helps.我希望这有帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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