Vibrate onclick

For Kotlin:

First of all, you have to add this to your Manifest

<uses-permission android:name="android.permission.VIBRATE"/>

Code:

private var vibration = activity?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

if (Build.VERSION.SDK_INT >= 26) {
    vibration.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
    vibrator.vibrate(200)
}

<uses-permission android:name="android.permission.VIBRATE" />

Be sure you added permission at AndroidManifest


is there a way to get a button to vibrate but only when the if condition is verified?

Yes. It looks like you have 95% of the code there already. Where did you get stuck?

You already have a Vibrator Object and a conditional. All you need to do now is call vibrate() like so:

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

if(l2 >= l1) {
    insertactone.setBackgroundColor(Color.RED);
    vibe.vibrate(100);
}

Don't forget that you need to add

<uses-permission android:name="android.permission.VIBRATE" />

in your AndroidManifest.xml file.