Nathaniel Cutajar
Nathaniel Cutajar

Reputation: 312

Need to toggle vibrator option on or off

I am currently building my first android application using android studio. I have a button pressing game and currently it vibrates when pressing a button during the game. I want to make a toggle to turn the button on and off. Currently, I have something like this:

public void onCheckBoxClicked(View view){
    Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    boolean checked = ((CheckBox)R.id.vibratecbx).isChecked();

    if(checked){
    }
    else{
        vibrate.cancel();
    }
}

I am receiving an error with regards to the line ((CheckBox)R.id.vibratecbx) with regards to incompatible types, so i'll need a fix on that, as well as to see how I can toggle the actual vibration option on or off for the game. Thank you :)

Here is the main game file section where the button is then being pressed:

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

            //vibrate on press
            Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            boolean isVibrator = vibrate.hasVibrator();
            if(isVibrator)
                vibrate.vibrate(50);

Upvotes: 1

Views: 361

Answers (1)

Gauthier
Gauthier

Reputation: 4978

((CheckBox)R.id.vibratecbx) doesn't give you a CheckBox.

If you want to use your CheckBox you need to get a reference to it from the xml you inflated.

For example in your Activity you could get your Checkbox during the onCreate

private CheckBox myCheckBox;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myCheckBox = (CheckBox) findViewById(R.id.vibratecbx);
    }

And then you can use myCheckBox as you wish.

EDIT

You can save the state of the CheckBox and use it when you click on a button. So that in your onClickListener you can check whether or not the app should vibrate.

As such :

    private CheckBox myCheckBox;
    private Vibrator myVibrator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myCheckBox = (CheckBox) findViewById(R.id.vibratecbx);

        myVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        ....
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ... your actions
                if(myVibrator.hasVibrator() && myCheckBox.isChecked())
                {
                    // Vibrate for 400 milliseconds
                    myVibrator.vibrate(400);
                }
            }
        });
       }

Upvotes: 1

Related Questions