Can any one tell how to implement RecyclerView Contextual Action Bar on long tap of listItem Selection on xamarin android?
Can any one tell how to implement RecyclerView Contextual Action Bar on long tap of listItem Selection on xamarin android?
Take Xamarin Official RecyclerViewer for example, you can follow the below steps to implement a contextual action bar on the recyclerview:
Create a simple menu resource for your action bar(Resource/menu/ContextualMenu
):
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/itemOneId"
android:title="Item One"/>
<item android:id="@+id/itemTwoId"
android:title="Item Two" />
</menu>
Create a class(MyActionMode
) implements ActionMode.ICallBack
:
public class MyActionMode : Java.Lang.Object, ActionMode.ICallback
{
private Context mContext;
public MyActionMode(Context context)
{
mContext = context;
}
public bool OnActionItemClicked(ActionMode mode, IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.itemOneId:
// do whatever you want
return true;
case Resource.Id.itemTwoId:
// do whatever you want
return true;
default:
return false;
}
}
public bool OnCreateActionMode(ActionMode mode, IMenu menu)
{
mode.MenuInflater.Inflate(Resource.Menu.ContextualMenu, menu);
return true;
}
public void OnDestroyActionMode(ActionMode mode)
{
mode.Dispose();
}
public bool OnPrepareActionMode(ActionMode mode, IMenu menu)
{
return false;
}
}
In PhotoViewHolder
modify the constructor to accept a long click action:
public PhotoViewHolder (View itemView, Action<int> listener,Action<object,View.LongClickEventArgs> longClickListener)
: base (itemView)
{
// Locate and cache view references:
Image = itemView.FindViewById<ImageView> (Resource.Id.imageView);
Caption = itemView.FindViewById<TextView> (Resource.Id.textView);
// Detect user clicks on the item view and report which item
// was clicked (by position) to the listener:
itemView.Click += (sender, e) => listener (base.Position);
ItemView.LongClick +=(sender,e)=> longClickListener(sender,e);
}
Modify PhotoAlbumAdapter
like this:
public class PhotoAlbumAdapter : RecyclerView.Adapter
{
...
// add this variable
private Activity mActivity;
//
private MyActionMode mActionMode;
...
// add this constructor
public PhotoAlbumAdapter(PhotoAlbum photoAlbum, Activity activity)
{
mPhotoAlbum = photoAlbum;
mActivity = activity;
}
//add this function
void OnLongClick(object sender, View.LongClickEventArgs args)
{
mActionMode = new MyActionMode(mActivity);
mActivity.StartActionMode(mActionMode);
((View)sender).Selected = true;
return;
}
...
}
In MainActivity
change the creation of PhotoAlbumAdapter
to use the newly created constructor:
mAdapter = new PhotoAlbumAdapter (mPhotoAlbum,this);
Here is the complete modified demo.