How to Implement Item Click Interface in Android?
When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application.
What we are going to build in this article?
In this article, we will be using a recycler view with many items. An item is made using CardView which further consists of TextView to show the required text to a user. When a user clicks on any item it displays the position and value of that item. Note that we are going to implement this project in Java Language. Here is a sample video of the application which we are going to build.
Step by Step Implementation
Step 1: Create a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Working with XML files
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.
Follow the path app > res > layout > right click > new > layout resource file and create a new file named as item_main.xml. Use the below code in item_main.xml file-
Step 3: Working with java files
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.
Follow the path app > java > com.example.multiple_item_delete > right click > new > java class and create a new file named as MainAdapter.java. Use the below code in MainAdapter.java file-
Follow the path app > java > com.example.multiple_item_delete > right click > new > interface and create a new file named as ItemClickListener.java. Use the below code in MainAdapter.java file-
Here is the final output of the application.