Can any one tell how to implement RecyclerView Contextual Action Bar on long tap of listItem Selection on xamarin android?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
) implementsActionMode.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 ofPhotoAlbumAdapter
to use the newly created constructor:mAdapter = new PhotoAlbumAdapter (mPhotoAlbum,this);
Here is the complete modified demo.
标签:
xamarin.android