本文介绍了如何保存工具按钮开/关选择的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经实现了基于切换按钮选择的应用程序.但是当我关闭该应用程序然后重新打开它时,它将进入其默认选择关闭".所以任何朋友都可以告诉 mw 我应该保存什么 togleButton 选择的状态并根据该 toggleButton 选择状态执行一些操作...谢谢.

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .Thanks.

推荐答案

使用 SharedPreferences.

Use SharedPreferences.

tg = (ToggleButton) findViewById(R.id.toggleButton1);

tg.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {

    if((tg.isChecked()))
        {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("tgpref", true); // value to store
                editor.commit();
        }
        else
        {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("tgpref", false); // value to store
                editor.commit();
        }
    }
});

这是检索值的方法:

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true);  //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
  tg.setChecked(true);
}
else
{
  tg.setChecked(false);
}

这段代码我没有验证,但是看看网上的一些例子,很简单!

I did not verify this code, but look at some examples on the net, it is easy!

这篇关于如何保存工具按钮开/关选择的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:32