home top ad

How to select multiple item in fragment using RecyclerView and listView in android

Hello Guys, today I will teach you how to select multiple item in andriod .Today lot of app implement this method because when you want select some item to download or share so you can use in method . Friends, today the need for multiple item selection is becoming more and today we implement it very easily in the activity.

What is the multiple item selection in fragment ?

Multisection is a method in which the user clicks on any item from the list for a long time, then add this selected item to a separate list, only then you can remove the previously selected data, while the user again on the same item Clicks.we will use 2 simple step to use this method in our app.

Create New Project

Start by creating a new Android project in Android studio. Choose "File", "New", select "New Project" and then click "Next". In the New Android Application window, enter your chosen Application, Project, and Package names and then choose "Next" and last finish. After creating the project, you will see two files, first activity_main and second MainActivity.java, then you have to paste the code given below activity_main and MainActivity.java.
After creating the project the first thing you can do is to see that in Gradle Scripts there is a library implementation 'com.google.android.material: material: 1.3.0', implementation 'androidx.recyclerview:recyclerview:1.2.0' implementation'androidx.cardview:cardview:1.0.0' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0 for design in build.gradle if not Add the dependency below to your build.gradle and hit the Sync Now button .

build.gradle
   implementation 'com.google.android.material:material:1.3.0'  
   implementation 'androidx.recyclerview:recyclerview:1.2.0'  
   implementation 'androidx.cardview:cardview:1.0.0'  
   implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'  

activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/coordinat_layout"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   <com.google.android.material.appbar.AppBarLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">  
     <androidx.appcompat.widget.Toolbar  
       android:id="@+id/toolbar"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       app:popupTheme="@style/ThemeOverlay.AppCompat.ActionBar"/>  
     <com.google.android.material.tabs.TabLayout  
       android:id="@+id/tab_layout"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       app:tabSelectedTextColor="@color/red"  
       app:tabTextColor="@color/white"  
       app:tabIndicatorHeight="2dp"  
       android:background="@color/purple_500"  
       app:tabIndicatorColor="#05F60F" />  
   </com.google.android.material.appbar.AppBarLayout>  
   <androidx.viewpager.widget.ViewPager  
     android:id="@+id/viewpager"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     app:layout_behavior="@string/appbar_scrolling_view_behavior" />  
 </androidx.coordinatorlayout.widget.CoordinatorLayout>  
Here you see that we have used an AppBarLayout, inside which the toolbar and tablayout have been used, and outside of AppBarLayout, we have used a ViewPager.
Now we are going to implement this activity_main in MainActivity.java

MainActivity.java
 import androidx.appcompat.app.AppCompatActivity;  
 import androidx.appcompat.widget.Toolbar;  
 import androidx.fragment.app.Fragment;  
 import androidx.viewpager.widget.ViewPager;  
 import android.os.Bundle;  
 import com.google.android.material.tabs.TabLayout;  
 public class MainActivity extends AppCompatActivity {  
   private static ViewPagerAdapter adapter;  
   TabLayout tabLayout;  
   ViewPager viewPager;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     Toolbar toolbar = findViewById(R.id.toolbar);  
     setSupportActionBar(toolbar);  
     viewPager = findViewById(R.id.viewpager);  
     setupViewPager(viewPager);//Set up View Pager  
     tabLayout = findViewById(R.id.tab_layout);  
     tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager  
   }  
   //Setting View Pager  
   private void setupViewPager(ViewPager viewPager) {  
       ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());  
     adapter.addFrag(new ListFragment(), "ListView");  
     adapter.addFrag(new RecycFragment(), "RecyclerView");  
     // tabLayout.setupWithViewPager(viewPager);  
     viewPager.setAdapter(adapter);  
   }  
   //adding fragments and title method  
   //Return current fragment on basis of Position  
   public Fragment getFragment(int pos) {  
     return adapter.getItem(pos);  
   }  
Here we have removed the default toolbar and replaced it with a new custom toolbar and then a method setupViewPager that is taking a parameter ViewPager to be created outside of onCreate. In this method, first we will get a ViewPagerAdapter class which we can create app. Clicking right above the package name of the package or right clicking on the error and clicking right will sugget us to create this class.
After creating the class, we will see two errors in the same method and the first ListFragment () and RecycFragment () will be done in the same way as the class created above whose code is given below.

ViewPagerAdapter.java
 import androidx.annotation.NonNull;  
 import androidx.fragment.app.Fragment;  
 import androidx.fragment.app.FragmentManager;  
 import androidx.fragment.app.FragmentPagerAdapter;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class ViewPagerAdapter extends FragmentPagerAdapter {  
   private final List<Fragment> mFragmentList = new ArrayList<>();//fragment array list  
   private final List<String> mFragmentTitleList = new ArrayList<>();//title array list  
   public ViewPagerAdapter(FragmentManager manager) {  
     super(manager);  
   }  
   @Override  
   public Fragment getItem(int position) {  
     return mFragmentList.get(position);  
   }  
   @Override  
   public int getCount() {  
     return mFragmentList.size();  
   }  
   //adding fragments and title method  
   public void addFrag(Fragment fragment, String title) {  
     mFragmentList.add(fragment);  
     mFragmentTitleList.add(title);  
   }  
   @Override  
   public CharSequence getPageTitle(int position) {  
     return mFragmentTitleList.get(position);  
   }  
 }  

ListFragment.java
 import android.os.Bundle;  
 import android.util.SparseBooleanArray;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.AdapterView;  
 import android.widget.ListView;  
 import android.widget.Toast;  
 import androidx.annotation.Nullable;  
 import androidx.appcompat.app.AppCompatActivity;  
 import androidx.appcompat.view.ActionMode;  
 import androidx.fragment.app.Fragment;  
 import java.util.ArrayList;  
 public class ListFragment extends Fragment {  
   private static View view;  
   private static ListAdapter adapter;  
   private static ListView listView;  
   //Action Mode for toolbar  
   private ActionMode mActionMode;  
   private static ArrayList<Model> item_models;  
   public ListFragment() {  
   }  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     view = inflater.inflate(R.layout.list_fragment, container, false);  
     populateListView();  
     implementListViewClickListeners();  
     return view;  
   }  
   //Populate ListView with dummy data  
   private void populateListView() {  
     listView = (ListView) view.findViewById(R.id.list_view);  
     item_models = new ArrayList<>();  
     for (int i = 1; i <= 40; i++)  
       item_models.add(new Model("Title " + i, "Sub Title " + i));  
     adapter = new ListAdapter(getActivity(), item_models);  
     listView.setAdapter(adapter);  
     adapter.notifyDataSetChanged();  
   }  
   //Implement item click and long click over listview  
   private void implementListViewClickListeners() {  
     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
       @Override  
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
         //If ActionMode not null select item  
         if (mActionMode != null)  
           onListItemSelect(position);  
       }  
     });  
     listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {  
       @Override  
       public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {  
         //Select item on long click  
         onListItemSelect(position);  
         return true;  
       }  
     });  
   }  
   //List item select method  
   private void onListItemSelect(int position) {  
     adapter.toggleSelection(position);//Toggle the selection  
     boolean hasCheckedItems = adapter.getSelectedCount() > 0;//Check if any items are already selected or not  
     if (hasCheckedItems && mActionMode == null)  
       // there are some selected items, start the actionMode  
       mActionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new Toolbar_ActionMode_Callback(getActivity(), null, adapter, item_models, true));  
     else if (!hasCheckedItems && mActionMode != null)  
       // there no selected items, finish the actionMode  
       mActionMode.finish();  
     if (mActionMode != null)  
       //set action mode title on item selection  
       mActionMode.setTitle(String.valueOf(adapter  
           .getSelectedCount()) + " selected");  
   }  
   //Set action mode null after use  
   public void setNullToActionMode() {  
     if (mActionMode != null)  
       mActionMode = null;  
   }  
   //Delete selected rows  
   public void deleteRows() {  
     SparseBooleanArray selected = adapter  
         .getSelectedIds();//Get selected ids  
     //Loop all selected ids  
     for (int i = (selected.size() - 1); i >= 0; i--) {  
       if (selected.valueAt(i)) {  
         //If current id is selected remove the item via key  
         item_models.remove(selected.keyAt(i));  
         adapter.notifyDataSetChanged();//notify adapter  
       }  
     }  
     Toast.makeText(getActivity(), selected.size() + " item deleted.", Toast.LENGTH_SHORT).show();//Show Toast  
     mActionMode.finish();//Finish action mode after use  
   }  
 }  
This is also useful for you

  • How to Create Image Slider using ViewPager in android studio
  • How to create Swipeable Videos Like TikTok Using ViewPager2 in andriod studio
  • how to get all audio files in android programmatically
  • How to use SearchView in andriod studio
  • How to check internet Connection in androd studio
  • How to Create Bottom Sheet in android studio
  • How to Refresh a list Using RecyclerView in Android Studio
  • How to create Welcome Splash Screen with animation in android studio
  • How to create menu and sub menu in android studio
  • How to create a list item with RecyclerView in Android Studio
  • BottomNavigationView android example
  • How to create Text to Speech app in android studio

  • list_fragment.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="match_parent"  
       android:background="#DF7F7F"  
       android:gravity="center"  
       android:orientation="vertical">  
       <!-- List View -->  
       <ListView  
         android:id="@+id/list_view"  
         android:layout_width="match_parent"  
         android:layout_height="match_parent"  
         android:scrollbars="none" />  
     </LinearLayout>  
    
    list_fragment is the xml file of ListFragment class to create this, when you open the res folder, you will see the layout folder in it, by right-clicking on this layout folder, you will create every layout that will be used in these class.
    list_fragment is the xml file of ListFragment class to create this, when you open the res folder, you will see the layout folder in it, by right-clicking on this layout folder, you will create every layout that will be used in these class.
    ListAdpter.java
     import android.content.Context;  
     import android.graphics.Color;  
     import android.util.SparseBooleanArray;  
     import android.view.LayoutInflater;  
     import android.view.View;  
     import android.view.ViewGroup;  
     import android.widget.BaseAdapter;  
     import android.widget.TextView;  
     import java.util.ArrayList;  
     public class ListAdapter extends BaseAdapter {  
       private Context context;  
       private ArrayList<Model> item_modelArrayList;  
       private SparseBooleanArray mSelectedItemsIds;  
       public ListAdapter(Context context, ArrayList<Model> item_modelArrayList) {  
         this.context = context;  
         this.item_modelArrayList = item_modelArrayList;  
         mSelectedItemsIds = new SparseBooleanArray();  
       }  
       @Override  
       public int getCount() {  
         return item_modelArrayList.size();  
       }  
       @Override  
       public Model getItem(int position) {  
         return item_modelArrayList.get(position);  
       }  
       @Override  
       public long getItemId(int position) {  
         return position;  
       }  
       @Override  
       public View getView(int position, View convertView, ViewGroup parent) {  
         LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
         ViewHolder holder;  
         if (convertView == null) {  
           convertView = inflater.inflate(R.layout.item, parent, false);  
           holder = new ViewHolder();  
           holder.title = (TextView) convertView.findViewById(R.id.title);  
           holder.sub_title = (TextView) convertView.findViewById(R.id.sub_title);  
           convertView.setTag(holder);  
         } else  
           holder = (ViewHolder) convertView.getTag();  
         holder.title.setText(item_modelArrayList.get(position).getTitle());  
         holder.sub_title.setText(item_modelArrayList.get(position).getSubTitle());  
         /** Change background color of the selected items in list view **/  
         convertView  
             .setBackgroundColor(mSelectedItemsIds.get(position) ? 0x9934B5E4  
                 : Color.TRANSPARENT);  
         return convertView;  
       }  
       private class ViewHolder {  
         TextView title, sub_title;  
       }  
       /***  
        * Methods required for do selections, remove selections, etc.  
        */  
       //Toggle selection methods  
       public void toggleSelection(int position) {  
         selectView(position, !mSelectedItemsIds.get(position));  
       }  
       //Remove selected selections  
       public void removeSelection() {  
         mSelectedItemsIds = new SparseBooleanArray();  
         notifyDataSetChanged();  
       }  
       //Put or delete selected position into SparseBooleanArray  
       public void selectView(int position, boolean value) {  
         if (value)  
           mSelectedItemsIds.put(position, value);  
         else  
           mSelectedItemsIds.delete(position);  
         notifyDataSetChanged();  
       }  
       //Get total selected count  
       public int getSelectedCount() {  
         return mSelectedItemsIds.size();  
       }  
       //Return all selected ids  
       public SparseBooleanArray getSelectedIds() {  
         return mSelectedItemsIds;  
       }  
     }  
    
    item.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="wrap_content"  
       android:background="#80000000"  
       android:orientation="vertical"  
       android:layout_marginTop="1dp"  
       android:padding="10dp">  
       <TextView  
         android:text="Title"  
         android:id="@+id/title"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:textColor="@android:color/black"  
         android:textSize="16sp" />  
       <TextView  
         android:text="Sub Title"  
         android:id="@+id/sub_title"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:textColor="@android:color/darker_gray"  
         android:textSize="13sp" />  
     </LinearLayout>  
    

    Model.java
     import java.io.Serializable;  
     public class Model implements Serializable {  
       /* Model class for List and Recycler Items */  
       private String title, subTitle;  
       public Model(String title, String subTitle) {  
         this.title = title;  
         this.subTitle = subTitle;  
       }  
       public String getTitle() {  
         return title;  
       }  
       public String getSubTitle() {  
         return subTitle;  
       }  
     }  
    
    RecycFragment.java
     import android.os.Bundle;  
     import android.util.SparseBooleanArray;  
     import android.view.LayoutInflater;  
     import android.view.View;  
     import android.view.ViewGroup;  
     import android.widget.Toast;  
     import androidx.annotation.Nullable;  
     import androidx.appcompat.app.AppCompatActivity;  
     import androidx.appcompat.view.ActionMode;  
     import androidx.fragment.app.Fragment;  
     import androidx.recyclerview.widget.LinearLayoutManager;  
     import androidx.recyclerview.widget.RecyclerView;  
     import java.util.ArrayList;  
     public class RecycFragment extends Fragment {  
       private static View view;  
       private static RecyclerView recyclerView;  
       private static ArrayList<Model> item_models;  
       private static RecycAdapter adapter;  
       private ActionMode mActionMode;  
       public RecycFragment() {  
       }  
       @Nullable  
       @Override  
       public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
         view = inflater.inflate(R.layout.recycler, container, false);  
         populateRecyclerView();  
         implementRecyclerViewClickListeners();  
         return view;  
       }  
       //Populate ListView with dummy data  
       private void populateRecyclerView() {  
         recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);  
         recyclerView.setHasFixedSize(true);  
         recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));  
         item_models = new ArrayList<>();  
         for (int i = 1; i <= 40; i++)  
           item_models.add(new Model("Title " + i, "Sub Title " + i));  
         adapter = new RecycAdapter(getActivity(), item_models);  
         recyclerView.setAdapter(adapter);  
         adapter.notifyDataSetChanged();  
       }  
       //Implement item click and long click over recycler view  
       private void implementRecyclerViewClickListeners() {  
         recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerClick_Listener() {  
           @Override  
           public void onClick(View view, int position) {  
             //If ActionMode not null select item  
             if (mActionMode != null)  
               onListItemSelect(position);  
           }  
           @Override  
           public void onLongClick(View view, int position) {  
             //Select item on long click  
             onListItemSelect(position);  
           }  
         }));  
       }  
       //List item select method  
       private void onListItemSelect(int position) {  
         adapter.toggleSelection(position);//Toggle the selection  
         boolean hasCheckedItems = adapter.getSelectedCount() > 0;//Check if any items are already selected or not  
         if (hasCheckedItems && mActionMode == null)  
           // there are some selected items, start the actionMode  
           mActionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new Toolbar_ActionMode_Callback(getActivity(),adapter, null, item_models, false));  
         else if (!hasCheckedItems && mActionMode != null)  
           // there no selected items, finish the actionMode  
           mActionMode.finish();  
         if (mActionMode != null)  
           //set action mode title on item selection  
           mActionMode.setTitle(String.valueOf(adapter  
               .getSelectedCount()) + " selected");  
       }  
       //Set action mode null after use  
       public void setNullToActionMode() {  
         if (mActionMode != null)  
           mActionMode = null;  
       }  
       //Delete selected rows  
       public void deleteRows() {  
         SparseBooleanArray selected = adapter  
             .getSelectedIds();//Get selected ids  
         //Loop all selected ids  
         for (int i = (selected.size() - 1); i >= 0; i--) {  
           if (selected.valueAt(i)) {  
             //If current id is selected remove the item via key  
             item_models.remove(selected.keyAt(i));  
             adapter.notifyDataSetChanged();//notify adapter  
           }  
         }  
         Toast.makeText(getActivity(), selected.size() + " item deleted.", Toast.LENGTH_SHORT).show();//Show Toast  
         mActionMode.finish();//Finish action mode after use  
       }  
     }  
    
    recycler.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="match_parent"  
       android:gravity="center"  
       android:background="#DF7F7F"  
       android:orientation="vertical">  
       <!-- Recycler View -->  
       <androidx.recyclerview.widget.RecyclerView  
         android:id="@+id/recyclerView"  
         android:layout_width="match_parent"  
         android:layout_height="match_parent"  
         android:scrollbars="none" />  
     </LinearLayout>  
    
    RecycAdapter.java
     import android.content.Context;  
     import android.graphics.Color;  
     import android.util.SparseBooleanArray;  
     import android.view.LayoutInflater;  
     import android.view.ViewGroup;  
     import androidx.recyclerview.widget.RecyclerView;  
     import java.util.ArrayList;  
     public class RecycAdapter extends RecyclerView.Adapter<DemoViewHolder> {  
       private ArrayList<Model> arrayList;  
       private Context context;  
       private SparseBooleanArray mSelectedItemsIds;  
       public RecycAdapter(Context context,  
                     ArrayList<Model> arrayList) {  
         this.context = context;  
         this.arrayList = arrayList;  
         mSelectedItemsIds = new SparseBooleanArray();  
       }  
       @Override  
       public int getItemCount() {  
         return (null != arrayList ? arrayList.size() : 0);  
       }  
       @Override  
       public void onBindViewHolder(DemoViewHolder holder,  
                      int position) {  
         //Setting text over text view  
         holder.title.setText(arrayList.get(position).getTitle());  
         holder.sub_title.setText(arrayList.get(position).getSubTitle());  
         /** Change background color of the selected items in list view **/  
         holder.itemView  
             .setBackgroundColor(mSelectedItemsIds.get(position) ? 0x9934B5E4  
                 : Color.TRANSPARENT);  
       }  
       @Override  
       public DemoViewHolder onCreateViewHolder(  
           ViewGroup viewGroup, int viewType) {  
         LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());  
         ViewGroup mainGroup = (ViewGroup) mInflater.inflate(  
             R.layout.item, viewGroup, false);  
         return new DemoViewHolder(mainGroup);  
       }  
       /***  
        * Methods required for do selections, remove selections, etc.  
        */  
       //Toggle selection methods  
       public void toggleSelection(int position) {  
         selectView(position, !mSelectedItemsIds.get(position));  
       }  
       //Remove selected selections  
       public void removeSelection() {  
         mSelectedItemsIds = new SparseBooleanArray();  
         notifyDataSetChanged();  
       }  
       //Put or delete selected position into SparseBooleanArray  
       public void selectView(int position, boolean value) {  
         if (value)  
           mSelectedItemsIds.put(position, value);  
         else  
           mSelectedItemsIds.delete(position);  
         notifyDataSetChanged();  
       }  
       //Get total selected count  
       public int getSelectedCount() {  
         return mSelectedItemsIds.size();  
       }  
       //Return all selected ids  
       public SparseBooleanArray getSelectedIds() {  
         return mSelectedItemsIds;  
       }  
     }  
    
    interface RecyclerClick_Listener
     import android.view.View;  
     public interface RecyclerClick_Listener {  
       /**  
        * Interface for Recycler View Click listener  
        **/  
       void onClick(View view, int position);  
       void onLongClick(View view, int position);  
     }  
    
    RecyclerTouchListener.java
     import android.content.Context;  
     import android.view.GestureDetector;  
     import android.view.MotionEvent;  
     import android.view.View;  
     import androidx.fragment.app.FragmentActivity;  
     import androidx.recyclerview.widget.RecyclerView;  
     public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {  
       private GestureDetector gestureDetector;  
       private RecyclerClick_Listener clickListener;  
       public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final RecyclerClick_Listener clickListener) {  
         this.clickListener = clickListener;  
         gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {  
           @Override  
           public boolean onSingleTapUp(MotionEvent e) {  
             return true;  
           }  
           @Override  
           public void onLongPress(MotionEvent e) {  
             View child = recyclerView.findChildViewUnder(e.getX(), e.getY());  
             if (child != null && clickListener != null) {  
               clickListener.onLongClick(child, recyclerView.getChildPosition(child));  
             }  
           }  
         });  
       }  
       @Override  
       public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {  
         View child = rv.findChildViewUnder(e.getX(), e.getY());  
         if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {  
           clickListener.onClick(child, rv.getChildPosition(child));  
         }  
         return false;  
       }  
       @Override  
       public void onTouchEvent(RecyclerView rv, MotionEvent e) {  
       }  
       @Override  
       public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {  
       }  
     }  
    
    Toolbar_ActionMode_Callback
    import android.content.Context;  
     import android.os.Build;  
     import android.util.Log;  
     import android.util.SparseBooleanArray;  
     import android.view.Menu;  
     import android.view.MenuItem;  
     import android.widget.Toast;  
     import androidx.appcompat.view.ActionMode;  
     import androidx.core.view.MenuItemCompat;  
     import androidx.fragment.app.Fragment;  
     import androidx.fragment.app.FragmentActivity;  
     import java.util.ArrayList;  
     public class Toolbar_ActionMode_Callback implements ActionMode.Callback {  
       private Context context;  
       private RecycAdapter recyclerView_adapter;  
       private ListAdapter listView_adapter;  
       private ArrayList<Model> message_models;  
       private boolean isListViewFragment;  
       public Toolbar_ActionMode_Callback(Context context, RecycAdapter recyclerView_adapter, ListAdapter listView_adapter, ArrayList<Model> message_models, boolean isListViewFragment) {  
         this.context = context;  
         this.recyclerView_adapter = recyclerView_adapter;  
         this.listView_adapter = listView_adapter;  
         this.message_models = message_models;  
         this.isListViewFragment = isListViewFragment;  
       }  
       @Override  
       public boolean onCreateActionMode(ActionMode mode, Menu menu) {  
         mode.getMenuInflater().inflate(R.menu.context_menu, menu);//Inflate the menu over action mode  
         return true;  
       }  
       @Override  
       public boolean onPrepareActionMode(ActionMode mode, Menu menu) {  
         //Sometimes the meu will not be visible so for that we need to set their visibility manually in this method  
         //So here show action menu according to SDK Levels  
         if (Build.VERSION.SDK_INT < 11) {  
           MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_delete), MenuItemCompat.SHOW_AS_ACTION_NEVER);  
           MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_copy), MenuItemCompat.SHOW_AS_ACTION_NEVER);  
           MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_forward), MenuItemCompat.SHOW_AS_ACTION_NEVER);  
         } else {  
           menu.findItem(R.id.action_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);  
           menu.findItem(R.id.action_copy).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);  
           menu.findItem(R.id.action_forward).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);  
         }  
         return true;  
       }  
       @Override  
       public boolean onActionItemClicked(ActionMode mode, MenuItem item) {  
         switch (item.getItemId()) {  
           case R.id.action_delete:  
             //Check if current action mode is from ListView Fragment or RecyclerView Fragment  
             if (isListViewFragment) {  
               Fragment listFragment = new MainActivity().getFragment(0);//Get list view Fragment  
               if (listFragment != null)  
                 //If list fragment is not null  
                 ((ListFragment) listFragment).deleteRows();//delete selected rows  
             } else {  
               //If current fragment is recycler view fragment  
               Fragment recyclerFragment = new MainActivity().getFragment(1);//Get recycler view fragment  
               if (recyclerFragment != null)  
                 //If recycler fragment not null  
                 ((RecycFragment) recyclerFragment).deleteRows();//delete selected rows  
             }  
             break;  
           case R.id.action_copy:  
             //Get selected ids on basis of current fragment action mode  
             SparseBooleanArray selected;  
             if (isListViewFragment)  
               selected = listView_adapter  
                   .getSelectedIds();  
             else  
               selected = recyclerView_adapter  
                   .getSelectedIds();  
             int selectedMessageSize = selected.size();  
             //Loop to all selected items  
             for (int i = (selectedMessageSize - 1); i >= 0; i--) {  
               if (selected.valueAt(i)) {  
                 //get selected data in Model  
                 Model model = message_models.get(selected.keyAt(i));  
                 String title = model.getTitle();  
                 String subTitle = model.getSubTitle();  
                 //Print the data to show if its working properly or not  
                 Log.e("Selected Items", "Title - " + title + "\n" + "Sub Title - " + subTitle);  
               }  
             }  
             Toast.makeText(context, "You selected Copy menu.", Toast.LENGTH_SHORT).show();//Show toast  
             mode.finish();//Finish action mode  
             break;  
           case R.id.action_forward:  
             Toast.makeText(context, "You selected Forward menu.", Toast.LENGTH_SHORT).show();//Show toast  
             mode.finish();//Finish action mode  
             break;  
         }  
         return false;  
       }  
       @Override  
       public void onDestroyActionMode(ActionMode mode) {  
         //When action mode destroyed remove selected selections and set action mode to null  
         //First check current fragment action mode  
         if (isListViewFragment) {  
           listView_adapter.removeSelection(); // remove selection  
           Fragment listFragment = new MainActivity().getFragment(0);//Get list fragment  
           if (listFragment != null)  
             ((ListFragment) listFragment).setNullToActionMode();//Set action mode null  
         } else {  
           recyclerView_adapter.removeSelection(); // remove selection  
           Fragment recyclerFragment = new MainActivity().getFragment(1);//Get recycler fragment  
           if (recyclerFragment != null)  
             ((RecycFragment) recyclerFragment).setNullToActionMode();//Set action mode null  
         }  
       }  
     }  
    
    Here you will see an error context_menu to fix it, you will be res >> new >> Android resource directory, after that you will see a resource type, after opening it, you will see a folder named menu and select the ok button on it. After that you will see the menu button, then by right-clicking on that menu folder, you create a menu layout and paste this code in it.

    context_menu.xml
     <menu 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"  
       tools:context=".MainActivity">  
       <!-- Toolbar ActionMode Menu Items -->  
       <item  
         android:id="@+id/action_delete"  
         android:icon="@drawable/delete"  
         android:orderInCategory="100"  
         android:title="delete"  
         app:showAsAction="ifRoom" />  
       <item  
         android:id="@+id/action_copy"  
         android:icon="@drawable/copy"  
         android:orderInCategory="100"  
         android:title="copy"  
         app:showAsAction="always" />  
       <item  
         android:id="@+id/action_forward"  
         android:icon="@drawable/far"  
         android:orderInCategory="100"  
         android:title="forward"  
         app:showAsAction="always" />  
     </menu>  
    
    If you are experiencing icon error, then you can right-click on the res folder and open the vector asset, select the icon of your choice and remove the error.
    And before running in the last, you open your value folder and open the Theme folder and paste this code in it.
    theme.xml
      <style name="Theme.MultipleSelectionProject" parent="Theme.MaterialComponents.DayNight.NoActionBar">  
         <!-- Primary brand color. -->  
         <item name="colorPrimary">@color/purple_500</item>  
         <item name="colorPrimaryVariant">@color/purple_700</item>  
         <item name="colorOnPrimary">@color/white</item>  
         <!-- Secondary brand color. -->  
         <item name="colorSecondary">@color/teal_200</item>  
         <item name="colorSecondaryVariant">@color/teal_700</item>  
         <item name="colorOnSecondary">@color/black</item>  
         <!-- Status bar color. -->  
         <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>  
         <!-- Customize your theme here. -->  
         <!-- It should be true otherwise action mode will not overlay toolbar -->  
         <item name="windowActionModeOverlay">true</item>  
         <!-- For Custom Action Mode Background Color/Drawable -->  
         <item name="actionModeBackground">@color/purple_500</item>  
       </style>  
    
    Here windowActionModeOverlay should be true otherwise it will not overlay the toolbar and in the actionModeBackground you can show the color code of the color you want by filling it in that color, you can show that instead of DarkActionbar we have to do NoActionBar.

    I hope that this article will be very useful for you.
    Thank You....

Post a Comment

0 Comments