How to Build a Simple Swiping Game in Android?
Last Updated :
16 Aug, 2024
In this article, we are going to create a simple swiping game using RecyclerView in Android Studio. RecyclerView is the ViewGroup that contains the views corresponding to your data. It’s a view itself, so you add RecyclerView into your layout the way you would add any other UI element. We are going to use ItemTouchHelper to implement the swiping feature. This class is designed to work with any LayoutManager but for certain situations, it can be optimized for your custom LayoutManager by extending methods in the ItemTouchHelper.Callback class or implementing ItemTouchHelper.ViewDropHandler interface in your LayoutManager.
What we are going to build in this article?
In this game, the player had to swipe the different colored bars to their corresponding sides. If it is a “Red” colored bar the player has to swipe it to the left side, If it is a “Yellow” colored bar the player has to swipe it to the Right side. If the player swiped correctly, he/she can continue the game. if the bar is swiped to the wrong side, the game will be ended and the player has to restart the game. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step-by-Step Implementation
Here are the steps we have to follow to create the game:
- Create a basic RecyclerView
- Create and Add bars to the RecyclerView
- Add the swiping feature to the RecyclerView by using ItemTouchHelper
- Add the game over Alert dialogue.
Important methods:
- attachToRecyclerView() -Attaches the ItemTouchHelper to the provided RecyclerView.
- SimpleCallback()– A simple wrapper to the default Callback which you can construct with drag and swipe directions and this class will handle the flag callbacks. You should still override onMove or onSwiped depending on your use case.
- onSwiped() – Used to implement the swinging function to the RecyclerView
Important Constants:
- LEFT – Left direction, used for swipe & drag control
- RIGHT – Right direction, used for swipe & drag control
Let’s build the simple swiping game using RecyclerView. We are going to implement this project using the Java Programming language.
Note:
For creating a new class:
For creating a new activity:
Step 1: Create a new project
First, we want to create a new project. To create a new project in Android Studio please refer to How to Create/Start a new project in Android Studio.
Step 2: Create the class files
In order to implement the basic RecyclerView, we have to create two new class files.
- Adapter class
- Model class
Navigation: app > java

Adapter class

Model class
Step 3: Create XML files
We have to create two XML files:
- In layout – bars.xml
- In drawable – shapeofthebar.xml
1. bars.xml
Navigation: app > res > layout

bars.xml
2. shapeofthebar.xml
Navigation: app > res > drawable

shapeofthebar.xml
Step 4: Working with activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

activity_main.xml
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Working with bars.xml file
Navigate to the app > res > layout and add the below code to that file. Below is the code for the bars.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/shapeofthebar"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:id="@+id/barlayout"
android:orientation="horizontal">
</LinearLayout>
Step 6: Working with shapeofthebar.xml file
Navigate to the app > res > drawable and add the below code to that file. Below is the code for the shapeofthebar.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:radius="19dp"/>
</shape>
Step 7: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
// Creating RecyclerView
private RecyclerView recyclerView;
// Creating a ArrayList of type Modelclass
private List<Modelclass> barsColor;
// Alert dialog
AlertDialog.Builder alertDialog;
private Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding elements to the barsColor
barsColor=new ArrayList<>();
Random random = new Random();
// Add 15 bars to the RecyclerView
for(int i=0;i<15;i++)
{
// Generate a random number
int n= random.nextInt(2);
// Giving the color for the
// bar based on the random number
if(n==0)
{
barsColor.add(new Modelclass("Yellow"));
}
else
{
barsColor.add(new Modelclass("Red"));
}
}
// Finding the RecyclerView by it's ID
recyclerView = findViewById(R.id.recyclerview);
// Creating an Adapter Object
adapter=new Adapter(this,barsColor);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Add ItemTouchHelper to the recyclerView
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
adapter.notifyDataSetChanged();
}
ItemTouchHelper.SimpleCallback simpleCallback= new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
// get the position of the swiped bar
int position = viewHolder.getPosition();
switch (direction) {
// Right side is for Yellow
case ItemTouchHelper.LEFT: {
if ((barsColor.get(position).getColor()).equals("Red")) {
barsColor.remove(position);
adapter.notifyDataSetChanged();
} else {
endthegame();
adapter.notifyDataSetChanged();
alertDialog.show();
}
break;
}
// Left side is for Red
case ItemTouchHelper.RIGHT: {
if ((barsColor.get(position).getColor()).equals("Yellow")) {
barsColor.remove(position);
adapter.notifyDataSetChanged();
} else {
endthegame();
adapter.notifyDataSetChanged();
alertDialog.show();
}
break;
}
}
}
};
// Shows game ended dialog
private void endthegame()
{
alertDialog=new AlertDialog.Builder(this);
alertDialog.setMessage("Oopa! Wrong side! Try Again! ").setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Later!", Toast.LENGTH_SHORT).show();
}
});
alertDialog.create();
}
}
Step 8: Working with the Adapter.java file
Below is the code for the Adapter.java file.
Java
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.ColorSpace;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import org.jetbrains.annotations.NotNull;
public class Adapter
extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<Modelclass> bars;
Context context;
Adapter(Context c, List<Modelclass> list)
{
bars = list;
context = c;
}
@NonNull
@NotNull
@Override
@SuppressLint("ResourceType")
public ViewHolder
onCreateViewHolder(@NonNull @NotNull ViewGroup parent,
int viewType)
{
View view
= LayoutInflater.from(parent.getContext())
.inflate(R.layout.bars, parent, false);
return new ViewHolder(view);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(
@NonNull @NotNull Adapter.ViewHolder holder,
int position)
{
// Getting the color for every position
String color = bars.get(position).getColor();
// Set the color to the bar
if (color.equals("Yellow")) {
holder.linearLayout.setBackgroundTintList(
context.getResources().getColorStateList(
R.color.yellow));
}
else {
holder.linearLayout.setBackgroundTintList(
context.getResources().getColorStateList(
R.color.Red));
}
}
@Override public int getItemCount()
{
return bars.size();
}
public class ViewHolder
extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
public ViewHolder(@NonNull @org.
jetbrains.annotations.
NotNull View itemView)
{
super(itemView);
linearLayout
= itemView.findViewById(R.id.barlayout);
}
}
}
Step 9: Working with the Modelclass.java file
Below is the code for the Modelclass.java file.
Java
public class Modelclass {
String color;
Modelclass(String color){
this.color=color;
}
public String getColor() {
return color;
}
}
Output:
Here is the output of our project.
Similar Reads
How to Build a Simple Reflex Game in Android?
A reflex game is a simple fun game that measures your responding speed. It is quite simple to make and understand. We will be designing a reflex game that will calculate your responding speed. The rules are simple just press the stop button when you see the change in background color, and the time y
4 min read
How to Build a Tic Tac Toe Game in Android?
In this article, we will be building a Tic Tac Toe Game Project using Java and XML in Android. The Tic Tac Toe Game is based on a two-player game. Each player chooses between X and O. The Player plays one move at a time simultaneously. In a move, a player can choose any position from a 3x3 grid. The
9 min read
How to Build a Simple Bill Splitter App in Android?
Many payment applications such as Paytm, PhonePe, and others provide the functionality to split the bills among a number of people to divide it equally. This is a very useful feature that helps users to split the bills amongst each other. In this article, we will take a look at How to create a simpl
4 min read
How to Build a Simple Notes App in Android?
Notes app is used for making short text notes, updating when you need them, and trashing when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick a
9 min read
How to Build a Rock Paper Scissor Game in Android Studio?
Rock Paper Scissor (which is also called Stone Paper Scissor) is a hand game and played between two people, in which each player simultaneously forms one of three shapes. The winner of the game is decided as per the below rules: Rock vs Paper -> Paper wins.Rock vs Scissor -> Rock wins.Paper vs
6 min read
How to Build a Dice Game in Java Android?
In this article, we will be building a Dice Game Project using Java/Kotlin and XML in Android. The Dice Game is based on a two-player dice game. Both dices are rolled and the winner result is displayed in a textview. There will be a single activity in this application. The result and a roll button w
4 min read
How to Build a Simple e-Crackers App using Android?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appHow to add Lottie Animation in an Android AppMediaPlayer Class in Android In this article, we are going to bui
12 min read
How to Build Spotify Clone in Android?
There are many android applications present in the market which are available to play songs on mobile phones. The famous one of all these music players is Spotify. In this article, we will be building a Spotify clone application using Spotify Web APIs. Step by Step ImplementationStep 1: Create a New
15+ min read
How to Build a Simple Voice Typer App in Android using Java?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appSpinner in AndroidRecognizerIntent in Android In this article, we are going to build a simple Voice Typer app
5 min read
How to Build a Simple Magic 8 Ball App in Android?
In this article, we will be building a Magic 8 Ball App Project using Java and XML in Android. The application is based on a decision making application. In this app, a user can ask the ball what decision they should make. The ball will randomly answer Yes, No, Not Sure, and other such answers. Ther
3 min read