0

我正在使用Toggle按钮,现在我必须control on state在切换时使用它,between activities并且我也能够控制状态,但即使切换状态off它仍在执行toggle on tasks

    boolean tg1pref;
    public SharedPreferences preferences;

    toggleMap = (ToggleButton) findViewById(R.id.toggleMap);
    toggleMap.setOnCheckedChangeListener(this);

        preferences = getApplicationContext().getSharedPreferences("tg1pref",0);

        tg1pref = preferences.getBoolean("tg1pref", true);
        if (tg1pref) {
            toggleMap.setChecked(true);
        } else {
            toggleMap.setChecked(false);
        }

    ...........
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {      

        if(isChecked)
        {   
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tg1pref", true); // value to store
            editor.commit();

            cd = new ConnectionDetector(getApplicationContext());
            // Check for internet connection
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(PunchInActivity.this, "Internet not available",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                return;
            }
            else 
            {                                    
                startTimer();   
            }

        } else 
        {               
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tg1pref", false); // value to store
            editor.commit();
        }
}
4

2 回答 2

0

我通过在 onResume() 中移动代码自己解决了我的问题

@Override
        protected void onResume() {
            super.onResume();

            tg1pref = preferences.getBoolean("tg1pref", true);
            if (tg1pref) {
                toggleMap.setChecked(true);
            } else {
                toggleMap.setChecked(false);
            }
        }
于 2015-01-16T09:59:55.173 回答
0
tg1pref = preferences.getBoolean("tg1pref", true);

在上面的行中使用false而不是 true。那应该行得通。

于 2015-01-16T09:56:37.487 回答