Open In App

How to Build a Simple Swiping Game in Android?

Last Updated : 23 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Output of this project

Step by Step Implementation

Here are the steps we have to follow to create the game:

  1. Create a basic RecyclerView
  2. Create and Add bars to the RecyclerView
  3. Add the swiping feature to the RecyclerView by using ItemTouchHelper
  4. 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.

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.

  1. Adapter class
  2. Model class

Navigation: app > java

Adapter class

Model class

Step 3: Create XML files

We have to create two XML files:

  1. In layout      – bars.xml
  2. 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.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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 
    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"?>
    <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 org.jetbrains.annotations.NotNull;
  
import java.util.List;
  
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.

Output of this project



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads