Xamarin.Android Recyclerview项目单击Listener无法正常工作

时间:2017-08-10 10:19:19

标签: c# android android-recyclerview xamarin.android recycler-adapter

Recyclerview项目点击不起作用。下面是我的适配器和ViewHolder的代码。我遵循可用的xamarin文档教程中的模式here

public class MainMenuRecyclerAdapter : RecyclerView.Adapter
{
    private readonly IList<ListMenuItem> items;



    public MainMenuRecyclerAdapter(IList<ListMenuItem> data)
    {
        items = data;
    }

    public override int ItemCount => items.Count;
    public event EventHandler<ClickEventArgs> ItemClick;
    public event EventHandler<ClickEventArgs> ItemLongClick;

    /// <summary>
    ///     Create new views (invoked by the layout manager)
    /// </summary>
    /// <param name="parent"></param>
    /// <param name="viewType"></param>
    /// <returns></returns>
    public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
    {
        //Setup your layout here
        const int id = Resource.Layout.MenuList;

        MainMenuRecyclerAdapterViewHolder vh;

        View itemView;
        using (itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false))
        {
            vh = new MainMenuRecyclerAdapterViewHolder(itemView, OnClick, OnLongClick);
        }
        return vh;
    }


    /// <summary>
    ///     Replace the contents of a view (invoked by the layout manager)
    /// </summary>
    /// <param name="viewHolder"></param>
    /// <param name="position"></param>
    public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
    {
        var item = items[position];
        // Replace the contents of the view with that element
        var holder = viewHolder as MainMenuRecyclerAdapterViewHolder;
        if (holder == null) return;
        holder.mnuHeader.Text = item.MenuHeader;

        holder.mnuDescription.Text = item.MenuDetails;

        switch (item.MenuKey)
        {
            case "CreateNew":
                holder.mnuIcon.SetImageResource(Resource.Drawable.createrecord);
                break;
            case "ViewRecords":
                holder.mnuIcon.SetImageResource(Resource.Drawable.vieweditrecord);
                break;
            case "SNR":
                holder.mnuIcon.SetImageResource(Resource.Drawable.keyinformantsubmissions);
                break;
            case "SNRLog":
                holder.mnuIcon.SetImageResource(Resource.Drawable.taskchecklist);
                break;
            case "AnalysisView":
                holder.mnuIcon.SetImageResource(Resource.Drawable.viewprogressreport);
                break;
            case "SendUpdates":
                holder.mnuIcon.SetImageResource(Resource.Drawable.syncwithserver);
                break;
            case "DeviceStatus":
                holder.mnuIcon.SetImageResource(Resource.Drawable.devicestatus);
                break;
            case "SystemSettings":
                holder.mnuIcon.SetImageResource(Resource.Drawable.settings);
                if (item.MenuDetails.Contains("Harare") && item.MenuKey == "SystemSettings")
                {
                    holder.mnuDescription.SetTextColor(Color.Green);
                    holder.mnuDescription.Text += " - TRAINING MODE";
                }
                if (!item.MenuDetails.Contains("Harare"))
                {
                    holder.mnuDescription.SetTextColor(Color.Red);
                    holder.mnuDescription.Text += " - VBCI MODE";
                }
                break;
            case "DBSettings":
                holder.mnuIcon.SetImageResource(Resource.Drawable.database);
                break;
            default:
                holder.mnuIcon.SetImageResource(Resource.Drawable.addbutton);
                break;
        }

    }

    private void OnClick(ClickEventArgs args)
    {
        ItemClick?.Invoke(this, args);
    }


    private void OnLongClick(ClickEventArgs args)
    {
        ItemLongClick?.Invoke(this, args);
    }
}

public class MainMenuRecyclerAdapterViewHolder : RecyclerView.ViewHolder
{
    public TextView mnuDescription;
    public TextView mnuHeader;
    public ImageView mnuIcon;


    public MainMenuRecyclerAdapterViewHolder(View itemView, Action<ClickEventArgs> clickListener,Action<ClickEventArgs> longClickListener) : base(itemView)
    {
        mnuHeader = itemView.FindViewById<TextView>(Resource.Id.txtMenuHeader);
        mnuDescription = itemView.FindViewById<TextView>(Resource.Id.txtMenuDetail);
        mnuIcon = itemView.FindViewById<ImageView>(Resource.Id.imgMenuIcon);

        itemView.Click += (sender, e) => clickListener(
            new ClickEventArgs { View = itemView, Position = AdapterPosition });

        itemView.LongClick +=(sender, e) => longClickListener(
                new ClickEventArgs { View = itemView, Position = AdapterPosition });
    }

}

public class ClickEventArgs : EventArgs
{
    public View View { get; set; }
    public int Position { get; set; }
}

我的活动代码

private void InitRecyclerView() {
        try
        {
            SetContentView(Resource.Layout.MainLayout);

            LoadMenuItems();

            dbPath = CheckDB();

            var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            toolbar.SetPadding(0, GetStatusBarHeight(), 0, 0);

            //Using the new recycler view
            recyclerView = FindViewById<RecyclerView>(Resource.Id.recycleView);

            recyclerView.SetLayoutManager(new LinearLayoutManager(this));

            mainMenuRecyclerAdapter = new MainMenuRecyclerAdapter(lstMnu);

            mainMenuRecyclerAdapter.ItemClick += RecyclerOnItemClick;

            recyclerView.SetAdapter(mainMenuRecyclerAdapter);
        }
        catch (Exception ex)
        {
            new AlertDialog.Builder(this)
                           .SetTitle("Homescreen - InitRecyclerView()")
                           .SetMessage("Error Occurred: " + ex.Message)
                           .SetPositiveButton("Ok", delegate { })
                           .Show();
        }}

我的XAML代码

    <android.support.design.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:layout_width="match_parent"
     android:layout_height="match_parent"
     android:fitsSystemWindows="true"><android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
      android:id="@+id/collapsingToolbar"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_scrollFlags="scroll|exitUntilCollapsed"
      android:fitsSystemWindows="true"
      app:contentScrim="@android:color/white"
      app:expandedTitleMarginStart="48dp"
      app:expandedTitleMarginEnd="64dp">
      <ImageView
        android:src="@drawable/RwimsHomeScreen"
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:scaleType="fitCenter"
        android:fitsSystemWindows="true"
        app:layout_collapseMode="parallax"
        android:background="@android:color/white"/>
      <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_collapseMode="pin" />
    </android.support.design.widget.CollapsingToolbarLayout>
  </android.support.design.widget.AppBarLayout>

  <android.support.v7.widget.RecyclerView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/recycleView"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
  </android.support.v7.widget.RecyclerView>

  <android.support.design.widget.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/ic_date_range_white_48dp"
    app:layout_anchor="@id/appBar"
    app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>

InitRecyclerView()函数是我在Activity OnCreateView方法上调用的函数。我的项目点击方法基本上如下所示:

private void RecyclerOnItemClick(object sender, ClickEventArgs e)
        {

                var vibrator = (Vibrator)GetSystemService(VibratorService);
                vibrator.Vibrate(60);

                switch (lstMnu[e.Position].MenuKey)
                {
                    case "CreateNew":
                        var intentCW = new Intent(this, typeof(ActFormSelectionMenu));
                        intentCW.PutExtra("CreateNew", "true");
                        StartActivity(intentCW);
                        break;
                    case "ViewRecords":
                        var intentVw = new Intent(this, typeof(ActFormSelectionMenu));
                        intentVw.PutExtra("CreateNew", "false");
                        StartActivity(intentVw);
                        break;
default:
                        Log.Debug("EmptyMenu", "---");
                        break;
                }
            }

MenuKeyListMenuItem对象的一个​​属性,它基本上包含其他属性,如description,header等。在初始化recyclerview之前,lstMnu变量被初始化并加载(通过另一种方法) 。 我无法弄清楚代码有什么问题,但不知何故,recyclelerview没有响应click事件。如果我将recyclerview更改为使用列表视图,菜单工作正常。帮帮我们。

1 个答案:

答案 0 :(得分:1)

  

Recyclerview项目点击不工作。

实际上确实如此,但它发生在您ImageView方法中定义的SetRecyclerAdaptor()中。

OnResume

注释掉上述代码将解决您的问题。