Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a ToggleButton change the functionality of other buttons in the same Activity?

Summed up, can a ToggleButton change what other buttons in the activity do when toggled? If so, a more specific explanation of what I want to do is below:

Basically there are three buttons and a togglebutton. When the togglebutton is toggled, pressing any of the three buttons will take a picture and 'save it' for that button. When untoggled, pressing any of the three buttons simply displays their images. I think I can figure out the camera capture part, but I need some direction when it comes to the togglebutton.

Any help is appreciated and I can explain further if necessary.

like image 298
rafvasq Avatar asked Jan 06 '23 16:01

rafvasq


2 Answers

What I would do is keep a couple flags for each state at the class level, like this:

public class MyClass {
   private static final int STATE_SAVE = 0;
   private static final int STATE_DISPLAY = 1;
   private int currentState = STATE_DISPLAY; 
   // I made this default for the example, 
   // you should use what makes sense to your project.
}

Then, inside your toggle button, you can set the flag. Paraphrasing this code since I don't have an editor open:

toggleButton.setOnToggleListener(new OnToggleListener() {
   @Override
   public void onToggled(boolean toggled) {
      if(toggled) {
         currentState = STATE_SAVE;
      } else {
         currentState = STATE_DISPLAY;
      }
   });

Now, when the buttons are clicked, you can switch based on the state to do an action:

button.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      if(currentState == STATE_SAVE) {
         // Save the image.
      } else if (currentState == STATE_DISPLAY) {
         // Display the image.
      }
   });
like image 83
AdamMc331 Avatar answered Jan 11 '23 02:01

AdamMc331


Create a boolean such as isToggleOn that is true or false depending on the ToggleButton. Then for each of your buttons, you can simply do:

Button button1 = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(isToggleOn){
            //do one thing
        } else {
            //do other thing
        }      
    }
});
like image 34
Bill Avatar answered Jan 11 '23 01:01

Bill