Vibration on button click in Android Studio
Add vibration permission
- AndroidManifest.xml
In your app's AndroidManifest.xml file, add the following line inside the
<manifest>
tag:
<uses-permission android:name="android.permission.VIBRATE" />
Here's the complete AndroidManifest.xml file:
AndroidManifest<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.johnpuwein">
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- activity_main.xml In your app's layout XML file, add a Button element with an id:
Here's the complete activity_main.xml file:
activity_main.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me" /></RelativeLayout>
- MainActivity.java In your app's Java file, add the following code to implement the onClick listener for the button:
MainActivity.javaimport android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
//John Puwein
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button buttonClick;
private Vibrator vibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize button and vibrator
buttonClick = findViewById(R.id.button_click);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Set onClick listener for button
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Vibrate the device
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(500);
}
}
});
}
}
In this code, we first initialize the button and the vibrator. Then, we set the onClick listener for the button. When the button is clicked, the vibrator vibrates for 500 milliseconds.
That's it! With these simple steps, you can add a vibration effect on button click in your Android app using Android Studio.
Comments
Post a Comment