RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible the construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of ListViews and GridViews. In this article, we are going to see how to select a single RadioButton while working on a RecyclerView.Â
What we are going to build in this article?
Here is a sample video of what we are going to build in this application. Note that we will be using Java language to make this project.
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.
- Name the application 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. Adding required dependency
Navigate to Gradle Scripts > gradle.scripts(module) and add the following dependency to it
implementation 'com.google.android.material:material:1.3.0'
Step 3. Working on 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.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout     android:layout_width = "match_parent"     android:layout_height = "match_parent"     android:padding = "16dp"     tools:context = ".MainActivity" >       < androidx.recyclerview.widget.RecyclerView         android:layout_width = "match_parent"         android:layout_height = "match_parent"         android:id = "@+id/recycler_view"         tools:listitem = "@layout/item_main" />   </ RelativeLayout > |
Navigate to app > res > layout > right-click > new > layout resource file and name it as item_main.xml. Use the following code in item_main.xml file-
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RadioButton     android:layout_width = "match_parent"     android:layout_height = "wrap_content"     android:id = "@+id/radio_button"     android:padding = "12dp"     android:textSize = "18sp"     android:textColor = "@android:color/darker_gray" > </ RadioButton > |
Step 4. Working on Java files
Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.
Java
package com.example.singleradiobuttonrv;   import android.os.Bundle; import android.service.autofill.LuhnChecksumValidator; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList;   public class MainActivity extends AppCompatActivity {     // Initialize variable     RecyclerView recyclerView;     ItemClickListener itemClickListener;     MainAdapter adapter;       @Override     protected void onCreate(Bundle savedInstanceState)     {         super .onCreate(savedInstanceState);         setContentView(R.layout.activity_main);           // Assign variable         recyclerView = findViewById(R.id.recycler_view);           // initialize array list         ArrayList<String> arrayList = new ArrayList<>();                 // Use for loop         for ( int i = 0 ; i < 20 ; i++) {             // add values in array list             arrayList.add( "RB " + i);         }           // Initialize listener         itemClickListener = new ItemClickListener() {             @Override public void onClick(String s)             {                 // Notify adapter                 recyclerView.post( new Runnable() {                     @Override public void run()                     {                         adapter.notifyDataSetChanged();                     }                 });                 // Display toast                 Toast                     .makeText(getApplicationContext(),                               "Selected : " + s,                               Toast.LENGTH_SHORT)                     .show();             }         };           // Set layout manager         recyclerView.setLayoutManager( new LinearLayoutManager( this ));           // Initialize adapter         adapter = new MainAdapter(arrayList, itemClickListener);           // set adapter         recyclerView.setAdapter(adapter);     } } |
Navigate to app > right-click > new > java class and name it as MainAdapter.java. Use the following code in it. Comments are added to the code to have a better understanding.
Java
package com.example.singleradiobuttonrv;   import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.RadioButton; import androidx.annotation.NonNull; import androidx.recyclerview.widget.AdapterListUpdateCallback; import androidx.recyclerview.widget.RecyclerView; import java.io.*; import java.util.ArrayList;   public class MainAdapter     extends RecyclerView.Adapter<MainAdapter.ViewHolder> {       // Initialize variable     ArrayList<String> arrayList;     ItemClickListener itemClickListener;     int selectedPosition = - 1 ;       // Create constructor     public MainAdapter(ArrayList<String> arrayList,                        ItemClickListener itemClickListener)     {         this .arrayList = arrayList;         this .itemClickListener = itemClickListener;     }       @NonNull     @Override     public ViewHolder     onCreateViewHolder( @NonNull ViewGroup parent,                        int viewType)     {         // Initialize view         View view = LayoutInflater.from(parent.getContext())                         .inflate(R.layout.item_main, parent,                                  false );         // Pass holder view         return new ViewHolder(view);     }       @Override     public void onBindViewHolder( @NonNull ViewHolder holder,                                  int position)     {         // Set text on radio button         holder.radioButton.setText(arrayList.get(position));                 // Checked selected radio button         holder.radioButton.setChecked(position                                       == selectedPosition);           // set listener on radio button         holder.radioButton.setOnCheckedChangeListener(             new CompoundButton.OnCheckedChangeListener() {                 @Override                 public void onCheckedChanged(                     CompoundButton compoundButton,                     boolean b)                 {                     // check condition                     if (b) {                         // When checked                         // update selected position                         selectedPosition                             = holder.getAdapterPosition();                         // Call listener                         itemClickListener.onClick(                             holder.radioButton.getText()                                 .toString());                     }                 }             });     }       @Override public long getItemId( int position)     {         // pass position         return position;     }     @Override public int getItemViewType( int position)     {         // pass position         return position;     }       @Override public int getItemCount()     {         // pass total list size         return arrayList.size();     }       public class ViewHolder         extends RecyclerView.ViewHolder {         // Initialize variable         RadioButton radioButton;           public ViewHolder( @NonNull View itemView)         {             super (itemView);               // Assign variable             radioButton                 = itemView.findViewById(R.id.radio_button);         }     } }   class GFG {     public static void main(String[] args)     {         System.out.println( "GFG!" );     } } |
Create a new interface and name it as ItemClickListener. Use the following code in the ItemClickListener.java file-
Java
package com.example.singleradiobuttonrv;   public interface ItemClickListener {     // Create method     void onClick(String s); } |
Here is the final output of our application.
Output: