更新使用复选框

时间:2015-08-20 22:33:09

标签: java android checkbox

我想在取消选中时更新更改并选中首选项活动中的复选框,但是当我按下后退按钮时它不起作用。它仅在我关闭活动然后打开它时才有效

主要活动

public class MainActivity extends ActionBarActivity   {
 private ToggleButton togle;
 private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Parameters params;
    private ShakeListener mShaker;
    MediaPlayer mp;
    ImageView anime;
    int p=1; 
@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    anime = (ImageView) findViewById(R.id.Animation);

    hasFlash = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        // device doesn't support flash
        // Show alert message and close the application
        AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
                .create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // closing the application
                finish();   }
        });
        alert.show();
        return;}


    getCamera();


    togle = (ToggleButton) findViewById(R.id.ToggleButton01);

    togle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
              boolean checked = ((ToggleButton) v).isChecked();
               if (checked){
                   turnOffFlash();
              }

               else{
                   getCamera();
                   turnOnFlash(); 
               }
                  }
        });


    SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean stopshake = getprefs.getBoolean("checkbox", true);
    if (stopshake == true ){

    mShaker = new ShakeListener(this); 
    mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
         public void onShake()
         { if (!isFlashOn) {
             Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();

             getCamera();
         turnOnFlash();
         }
         else{
               turnOffFlash();

               Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();   
         } }
       });
         }


    }

private void getCamera() {
    // TODO Auto-generated method stub
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
        }
    } }

private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }
        // play sound
        getCamera();
        playSound();

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;
        anime.setImageResource(R.drawable.anim);
        anime.post(new Runnable() {
            @Override
            public void run() {
                AnimationDrawable frameAnimation =
                    (AnimationDrawable) anime.getDrawable(); 
                frameAnimation.start();
            }
        });

        // changing button/switch image
    }
  }

 private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }
            // play sound
            playSound();

            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
            isFlashOn = false;
            anime.setImageResource(R.drawable.off);
            // changing button/switch image
        }
    }

private void playSound() {
    // TODO Auto-generated method stub
     if(isFlashOn){
            mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
        }else{
            mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
        }
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }
        }); 
        mp.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent(MainActivity.this, Prefsetting.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

 }

偏好活动

public class Prefsetting extends PreferenceActivity   {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.prefset);

}

  }

2 个答案:

答案 0 :(得分:0)

从代码片段看,您似乎从未真正将更改提交到应用程序的SharedPreferences。在翻转布尔值时,代码中的某处需要执行以下操作:

prefs.put("checkbox", currentBooleanState).commit();

答案 1 :(得分:0)

您可以访问SharedPreferences onCreate()中的MainActivity,只有在从头开始创建该活动时(即首次启动应用时),才会调用Prefsetting。当您(可能)相当快地导航到MainActivity活动时,Activity可能仅在恢复时处于暂停或停止状态。看一下diagram here,了解@Override public void onResume() { super.onResume(); SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); boolean stopshake = getprefs.getBoolean("checkbox", true); if (stopshake) { mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () { public void onShake() { if (!isFlashOn) { Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show(); getCamera(); turnOnFlash(); } else { turnOffFlash(); Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show(); } } }); } else { if (mShaker != null) { mShaker.setOnShakeListener(null); mShaker = null; } } } 课程在进出前台时会发生什么。

你有几个选择。要么放这个:

onResume()

进入像EventBus这样的地方。

或者,在onPause()调用PreferenceActivity时,使用{{1}} LocalBrodcastManager来更新您的偏好设置。