Ejemplo n.º 1
0
        public bool OnInterceptTouchEvent (RecyclerView rv, MotionEvent e)
        {
            // TODO : this part intercep any touch inside recycler
            // and delete pending items.
            // A better method could be used.

            if (e.Action == MotionEventActions.Down) {
                var undoAdapter = (IUndoAdapter)rv.GetAdapter ();
                View view = GetChildViewUnder (e);

                if (view == null) {
                    undoAdapter.DeleteSelectedItem ();
                } else {
                    int position = recyclerView.GetChildLayoutPosition (view);
                    if (!undoAdapter.IsUndo (position)) {
                        undoAdapter.DeleteSelectedItem ();
                    }
                }
            }

            if (IsEnabled) {
                gestureDetector.OnTouchEvent (e);
            }
            return false;
        }
        public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            base.OnScrolled (recyclerView, dx, dy);

            var visibleItemCount = recyclerView.ChildCount;
            var totalItemCount = recyclerView.GetAdapter().ItemCount;
            var pastVisiblesItems = LayoutManager.FindFirstVisibleItemPosition();

            if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                LoadMoreEvent (this, totalItemCount);
            }
        }
        protected virtual void CleanUpReferencesToViewOrContext()
        {
            recycler?.GetAdapter()?.Dispose();
            recycler?.Dispose();
            viewSwitcher = null;
            header       = null;
            emptyText    = null;

            if (loadMoreButton != null)
            {
                loadMoreButton.Click -= NextButon_Click;
            }

            loadMoreButton = null;
            LoadMoreClick  = null;
        }
        public virtual void AddColumnItems(int column, IList <ICell> cellColumnItems)
        {
            // It should be same size with exist model list.
            if (cellColumnItems.Count != mItemList.Count || cellColumnItems.Contains(null))
            {
                return;
            }

            // Firstly, add columns from visible recyclerViews.
            // To be able provide removing animation, we need to notify just for given column position.
            CellLayoutManager layoutManager = mTableView.GetCellLayoutManager();

            for (int i = layoutManager.FindFirstVisibleItemPosition();
                 i < layoutManager.FindLastVisibleItemPosition() + 1;
                 i++)
            {
                // Get the cell row recyclerView that is located on i position
                RecyclerView cellRowRecyclerView = (RecyclerView)layoutManager.FindViewByPosition(i);
                // Add the item using its adapter.
                ((AbstractRecyclerViewAdapter <ICell>)cellRowRecyclerView.GetAdapter()).AddItem(column,
                                                                                                cellColumnItems[i]);
            }

            // Lets change the model list silently
            IList <IList <ICell> > cellItems = new AList <IList <ICell> >();

            for (int i_1 = 0; i_1 < mItemList.Count; i_1++)
            {
                IList <ICell> rowList = new AList <ICell>((IList <ICell>)mItemList[i_1]);
                if (rowList.Count > column)
                {
                    rowList.Insert(column, cellColumnItems[i_1]);
                }

                cellItems.Add(rowList);
            }

            // Change data without notifying. Because we already did for visible recyclerViews.
            SetItems(cellItems, false);
        }
Ejemplo n.º 5
0
        /**Turn By Turn Navigation Ui**/

        private void reconfigureUiForNavigation(int itineraryIndex)
        {
            //Disable the actv layout, and route/start buttons
            FindViewById <LinearLayout>(Resource.Id.actvLayout).Visibility = ViewStates.Gone;
            FindViewById <Button>(Resource.Id.startButton).Visibility      = ViewStates.Gone;
            FindViewById <Button>(Resource.Id.routeButton).Visibility      = ViewStates.Gone;

            //Binds a variable to the recyclerView
            RecyclerView recyclerView = FindViewById <RecyclerView>(Resource.Id.slidingRecycler);

            //Parses the itinerary selected
            Itinerary itin = OtpAPI.ParseItinerary(otpResponse["plan"]["itineraries"][itineraryIndex]);

            //Binds a variable to a configured recycler view
            recyclerView = Tools.configureRecyclerViewForNavigation(itin, recyclerView);

            //Sets up the turn by turn ui (the upper section)
            initializeUpperNavigationUi(itin, recyclerView);

            //Sets the first row in the recyclerView to be highlighted
            ((StepRowAdapter)recyclerView.GetAdapter()).HighlightedRow = 0;

            //Hides the recentering button when navigating
            Tools.toggleVisibility(FindViewById <FloatingActionButton>(Resource.Id.recenterOnUserActionButton));

            //Binds the backToRoutingButton to go back to the routing screen
            Button backToRoutingButton = FindViewById <Button>(Resource.Id.backToRoutingButton);

            backToRoutingButton.Click += delegate
            {
                //TODO: implement reverse screen reconfiguration
                reconfigureUiForRouting();
            };

            //Configures the station image thumbnail with the sample image
            configureStationImage();

            //Starts turn by turn tracking for stepping through the steps
            initializeTurnByTurnTracking(itin, recyclerView);
        }
Ejemplo n.º 6
0
            public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                try
                {
                    base.OnScrolled(recyclerView, dx, dy);

                    var visibleItemCount = recyclerView.ChildCount;
                    var totalItemCount   = recyclerView.GetAdapter().ItemCount;

                    int[] firstVisibleItemPositions;

                    // Check if we're running on Android 5.0 or higher
                    if ((int)Build.VERSION.SdkInt < 23)
                    {
                        firstVisibleItemPositions = new int[2];
                    }
                    else
                    {
                        firstVisibleItemPositions = new int[3];
                    }

                    var firstVisibleItem =
                        ((StaggeredGridLayoutManager)recyclerView.GetLayoutManager()).FindFirstVisibleItemPositions(
                            firstVisibleItemPositions)[0];

                    var pastVisiblesItems = firstVisibleItem;
                    if (visibleItemCount + pastVisiblesItems + 8 >= totalItemCount)
                    {
                        if (IsLoading == false)
                        {
                            LoadMoreEvent?.Invoke(this, null);
                            IsLoading = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Crashes.TrackError(exception);
                }
            }
        public override void OnDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)
        {
            int left  = parent.PaddingLeft;
            int right = parent.Width - parent.PaddingRight;

            int childCount = parent.GetAdapter().ItemCount;

            for (int i = 0; i < childCount; i++)
            {
                var child = parent.GetChildAt(i);

                if (child == null)
                {
                    return;
                }

                var lp = (RecyclerView.LayoutParams)child.LayoutParameters;

                int top = (int)(child.Top + lp.TopMargin + lp.BottomMargin + child.TranslationY);

                c.DrawLine(left + ((i + 1 < childCount) ? _sideSpace : 0), top, right, top, _paint);
            }
        }
Ejemplo n.º 8
0
        protected override void OnStart()
        {
            base.OnStart();

            if (DataManager.LoginImpossible)
            {
                StartUserActivity();
                return;
            }

            if (_recyclerView.GetAdapter() == null)
            {
                _machines.Clear();
                _adapter = new MachinesAdapter(_machines);
                _recyclerView.SetAdapter(_adapter);
                _adapter.ItemClicked += StartSelectedMachineActivity;

                DataManager.SheduleGetMachinesRequest(DataUpdateCallback);
                _lastUpdateTime = DateTime.Now;
            }

            _timerHolder.Start();
        }
Ejemplo n.º 9
0
        public override void OnDrawOver(Canvas cValue, RecyclerView parent, RecyclerView.State state)
        {
            var left  = parent.PaddingLeft;
            var right = parent.Width - parent.PaddingRight;

            for (var i = 0; i < parent.ChildCount; i++)
            {
                var child = parent.GetChildAt(i);

                var parameters = child.LayoutParameters.JavaCast <RecyclerView.LayoutParams>();

                var top    = child.Bottom + parameters.BottomMargin;
                var bottom = top + _divider.IntrinsicHeight;

                _divider.SetBounds(left, top, right, bottom);

                if ((parent.GetChildAdapterPosition(child) == parent.GetAdapter().ItemCount - 1) && parent.Bottom < bottom)
                { // this prevent a parent to hide the last item's divider
                    parent.SetPadding(parent.PaddingLeft, parent.PaddingTop, parent.PaddingRight, bottom - parent.Bottom);
                }

                _divider.Draw(cValue);
            }
        }
            public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                try
                {
                    base.OnScrolled(recyclerView, dx, dy);

                    var visibleItemCount = recyclerView.ChildCount;
                    var totalItemCount   = recyclerView.GetAdapter().ItemCount;

                    var pastVisiblesItems = LayoutManager.FindFirstVisibleItemPosition();
                    if (visibleItemCount + pastVisiblesItems + 8 >= totalItemCount)
                    {
                        if (IsLoading == false)
                        {
                            LoadMoreEvent?.Invoke(this, null);
                            IsLoading = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }
        public override void OnDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)
        {
            base.OnDrawOver(c, parent, state);
            int itemCount = parent.GetAdapter().ItemCount;

            // center horizontally, calculate width and subtract half from center
            float totalLength         = mIndicatorItemLength * itemCount;
            float paddingBetweenItems = Math.Max(0, itemCount - 1) * mIndicatorItemPadding;
            float indicatorTotalWidth = totalLength + paddingBetweenItems;
            float indicatorStartX     = (parent.Width - indicatorTotalWidth) / 2F;

            float indicatorPosY = parent.Height - mIndicatorHeight / 2F;

            drawInactiveIndicators(c, indicatorStartX, indicatorPosY, itemCount);


            // find active page (which should be highlighted)
            LinearLayoutManager layoutManager = (LinearLayoutManager)parent.GetLayoutManager();
            int activePosition = layoutManager.FindLastVisibleItemPosition();

            if (activePosition == RecyclerView.NoPosition)
            {
                return;
            }

            // find offset of active page (if the user is scrolling)
            View activeChild = layoutManager.FindViewByPosition(activePosition);
            int  left        = activeChild.Left;
            int  width       = activeChild.Width;

            // on swipe the active item will be positioned from [-width, 0]
            // interpolate offset for smooth animation
            float progress = mInterpolator.GetInterpolation(left * -1 / (float)width);

            drawHighlights(c, indicatorStartX, indicatorPosY, activePosition, progress, itemCount);
        }
 private int getTotalItemCount(RecyclerView parent)
 {
     return(parent.GetAdapter().ItemCount);
 }
Ejemplo n.º 13
0
        public bool CanDismiss(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
        {
            var adapter = recyclerView.GetAdapter();

            return(adapter.GetItemViewType(viewHolder.LayoutPosition) == LogTimeEntriesAdapter.ViewTypeContent);
        }
Ejemplo n.º 14
0
            public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                View firstVisibleView 	= recyclerView.GetChildAt(0);
                int firstVisiblePosition = recyclerView.GetChildPosition(firstVisibleView);
                int visibleRange 		= recyclerView.ChildCount;
                int lastVisiblePosition = firstVisiblePosition + visibleRange;
                int itemCount 			= recyclerView.GetAdapter().ItemCount;
                int position;

                if(firstVisiblePosition==0)
                    position=0;
                else if(lastVisiblePosition==itemCount-1)
                    position = itemCount-1;
                else
                    position = firstVisiblePosition;

                float proportion=(float)position/(float)itemCount;
                this.scroll.setPosition(scroll.height*proportion);
            }
Ejemplo n.º 15
0
		public override void OnScrolled (RecyclerView recyclerView, int dx, int dy)
		{
			pref = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
			LinearLayoutManager linearLayoutManager = (LinearLayoutManager)recyclerView.GetLayoutManager ();
			int lastVisibleItem = linearLayoutManager.FindLastVisibleItemPosition();
			int totalItemCount = recyclerView.GetAdapter().ItemCount;

			if (!IsLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
				// End has been reached
				// Do something
				var currPrefPage = pref.GetString ("CurrentPage", string.Empty);
				if (!String.IsNullOrEmpty (currPrefPage)) {
					if (Int32.Parse (currPrefPage) > 0) {
						currentPage++;
					} else {
						currentPage = 2;
					}
				} else {
					currentPage++;

				}
				var editor = pref.Edit();
				editor.PutString("CurrentPage",currentPage.ToString());
				editor.Apply();

				IsLoading = true;
				Task.Factory.StartNew (async () => {
					
					try{
						var newPostList = new List<Post>();
						await WebClient.LoadPosts(newPostList,currentPage);


						(recyclerView.GetAdapter()as PostViewAdapter)._Posts.AddRange(newPostList);
						//recyclerView.GetAdapter().HasStableIds = true;

						_messageShown = false;
						Application.SynchronizationContext.Post (_ => {recyclerView.GetAdapter().NotifyDataSetChanged();}, null);
						//recyclerView.GetAdapter().NotifyItemRangeInserted(recyclerView.GetAdapter().ItemCount,newPostList.Count);
					}catch(Exception ex){
						//Insights.Report(ex,new Dictionary<string,string>{{"Message",ex.Message}},Insights.Severity.Error);
						var text = ex.Message;
						if(!_messageShown){
							Application.SynchronizationContext.Post (_ => {
								Toast.MakeText(Application.Context,"При загрузке данных произошла ошибка",ToastLength.Short).Show();
							}, null);
							_messageShown = true;
						}

					}


					IsLoading = false;
				});

			}
		}
        public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
        {
            int left, top, right, bottom;

            left = right = top = bottom = _space / 2;

            bool isViewEdgeLeft           = false;
            bool isViewEdgeTop            = false;
            bool isViewEdgeRight          = false;
            bool isViewEdgeBottom         = false;
            bool horizontalOffsetAssigned = false;

            int viewPosition = parent.GetChildAdapterPosition(view);
            int viewCount    = parent.GetAdapter().ItemCount;

            if (parent.GetLayoutManager() is ResponsiveGridLayoutManager responsiveGridLayout)
            {
                int spanCount = responsiveGridLayout.SpanCount;
                isViewEdgeLeft   = viewPosition % spanCount == 0;
                isViewEdgeTop    = viewPosition < spanCount;
                isViewEdgeRight  = viewPosition % spanCount == spanCount - 1;
                isViewEdgeBottom = viewPosition / spanCount == viewCount - 1 / spanCount;

                if (responsiveGridLayout.TryGetItemWidth(out int itemWidth))
                {
                    int gridLeftPadding  = _leftPadding;
                    int gridRightPadding = _rightPadding;
                    if (spanCount == 1)
                    {
                        // If there is only one column we want our items centered
                        gridLeftPadding          = 0;
                        gridRightPadding         = 0;
                        horizontalOffsetAssigned = true;
                    }

                    int availableWidthSpace = parent.Width - gridLeftPadding - gridRightPadding - spanCount * itemWidth;
                    int interItemSpacing    = spanCount > 1 ? availableWidthSpace / (spanCount - 1) : availableWidthSpace;
                    left = right = interItemSpacing / 2;
                }
            }
            else if (parent.GetLayoutManager() is LinearLayoutManager)
            {
                isViewEdgeLeft  = viewPosition == 0;
                isViewEdgeTop   = isViewEdgeBottom = true;
                isViewEdgeRight = viewPosition == viewCount - 1;
            }

            if (isViewEdgeLeft && !horizontalOffsetAssigned)
            {
                left = _leftPadding;
            }

            if (isViewEdgeRight && !horizontalOffsetAssigned)
            {
                right = _rightPadding;
            }

            if (isViewEdgeTop)
            {
                top = _topPadding;
            }

            if (isViewEdgeBottom)
            {
                bottom = _bottomPadding;
            }

            outRect.Left   = left;
            outRect.Top    = top;
            outRect.Right  = right;
            outRect.Bottom = bottom;
        }
Ejemplo n.º 17
0
 protected override void OnSaveInstanceState(Bundle outState)
 {
     base.OnSaveInstanceState(outState);
     ((MyExRecyclerViewAdapter)myRecyclerView.GetAdapter()).OnSaveInstanceState(outState);
 }
Ejemplo n.º 18
0
        protected override void OnDestroy()
        {
            _contactsRecyclerView.GetAdapter().Dispose();

            base.OnDestroy();
        }
Ejemplo n.º 19
0
 public void UpdateAdapter(string url, List <Tuple <string, int> > selectedIngrForSearchRecipe = null)
 {
     loadRecipesThread = new Thread(new ThreadStart(() =>
     {
         try
         {
             HttpWebRequest request;
             HttpWebResponse response;
             HtmlDocument htmlDocument = new HtmlDocument();
             StreamReader streamFormater;//для перекодировки текста
             try
             {
                 if (parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility == ViewStates.Invisible || parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility == ViewStates.Gone)
                 {
                     Activity.RunOnUiThread(() => parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility = ViewStates.Visible);
                 }
             }
             catch (NullReferenceException)
             { }
             for (int i = 0; i < 10; i++)
             {
                 url      = url.Replace(("~" + i), ("~" + (i + 1)));
                 request  = (HttpWebRequest)WebRequest.Create(url);
                 response = (HttpWebResponse)request.GetResponse();
                 htmlDocument.Load(response.GetResponseStream(), Encoding.GetEncoding("windows-1251"));
                 for (int j = 0; j < 15; j++)
                 {
                     try
                     {
                         var recipeHtml = htmlDocument.DocumentNode.Descendants("table").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "uno_recipie");
                         //блок с рецептoм
                         var descHtml = recipeHtml.Descendants("td").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "recipe-list-right-col");
                         //категории рецепта
                         var categoriesHtml        = descHtml.Descendants("nobr").ToList();
                         List <string> mCategories = new List <string>();
                         foreach (var item in categoriesHtml)
                         {
                             streamFormater   = new StreamReader(GenerateStreamFromString(item.FirstChild.InnerText.Trim()), Encoding.UTF8);
                             string categorie = streamFormater.ReadLine();
                             mCategories.Add(categorie);
                         }
                         //тэги рецепта
                         var tagHtml         = recipeHtml.Descendants("div").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "recipie_tags").Descendants("span").ToList();
                         List <string> mTags = new List <string>();
                         foreach (var item in tagHtml)
                         {
                             streamFormater = new StreamReader(GenerateStreamFromString(item.FirstChild.InnerText.Trim()), Encoding.UTF8);
                             string tag     = streamFormater.ReadLine();
                             mTags.Add(tag);
                         }
                         //название
                         string name = recipeHtml.Descendants("a").FirstOrDefault(x => x.Attributes.Contains("href") && x.Attributes.Contains("title")).InnerText.Trim();
                         name        = name.Replace("&quot;", "");
                         //создается поток с кодировкой utf-8
                         streamFormater = new StreamReader(GenerateStreamFromString(name), Encoding.UTF8);
                         name           = streamFormater.ReadLine();
                         //описание
                         string description = descHtml.ChildNodes[0].InnerText.Trim();
                         streamFormater     = new StreamReader(GenerateStreamFromString(description), Encoding.UTF8);
                         description        = streamFormater.ReadLine();
                         //ссылка
                         string recipeLink = recipeHtml.Descendants("a").FirstOrDefault(x => x.Attributes.Contains("href")).Attributes["href"].Value;
                         //изображение
                         string imageUrl = null;
                         imageUrl        = GetImageFromUrl(recipeLink);
                         //время приготовления
                         string time = GetTimeRecipeFromUrl(recipeLink);
                         //ингридиенты
                         List <string> _listIngr = new List <string>();
                         var html     = recipeHtml.Descendants("div").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "ingr_fast");
                         var ingrHtml = html.FirstChild.FirstChild.FirstChild;
                         foreach (var item in ingrHtml.ChildNodes)
                         {
                             //Console.WriteLine(item.Name);
                             foreach (var item2 in item.ChildNodes)
                             {
                                 foreach (var item3 in item2.ChildNodes)
                                 {
                                     streamFormater = new StreamReader(GenerateStreamFromString(item3.InnerText.Trim()), Encoding.UTF8);
                                     _listIngr.Add(streamFormater.ReadLine());
                                 }
                             }
                         }
                         //поиск на совпадение ингредиентов
                         if (selectedIngrForSearchRecipe != null)
                         {
                             foreach (var ingr in _listIngr)
                             {
                                 if (selectedIngrForSearchRecipe.Any(c => c.Item1 == ingr))
                                 {
                                     mRecipe.Add(new Recipe
                                     {
                                         Name        = name,
                                         Link        = recipeLink,
                                         ImageUrl    = imageUrl != null ? imageUrl : "https://pp.userapi.com/c604426/v604426563/5a9d/xplUnWS7EFA.jpg",
                                         Description = description,
                                         Category    = mCategories,
                                         Tags        = mTags,
                                         Time        = time != null ? time : "-",
                                         IngrList    = _listIngr
                                     });
                                     //Activity.RunOnUiThread(() => recyclerView.GetAdapter().NotifyItemInserted(mRecipe.Count));
                                     break;
                                 }
                             }
                         }
                         else
                         {
                             mRecipe.Add(new Recipe
                             {
                                 Name        = name,
                                 Link        = recipeLink,
                                 ImageUrl    = imageUrl != null ? imageUrl : "https://pp.userapi.com/c604426/v604426563/5a9d/xplUnWS7EFA.jpg",
                                 Description = description,
                                 Category    = mCategories,
                                 Tags        = mTags,
                                 Time        = time != null ? time : "-",
                                 IngrList    = _listIngr
                             });
                         }
                         htmlDocument.DocumentNode.Descendants("table").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "uno_recipie").Remove();
                         Activity.RunOnUiThread(() => recyclerView.GetAdapter().NotifyItemInserted(mRecipe.Count));
                         if (parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility == ViewStates.Visible || parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility == ViewStates.Gone)
                         {
                             Activity.RunOnUiThread(() => parentView.FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility = ViewStates.Invisible);
                         }
                     }
                     catch (System.NullReferenceException)
                     {
                         continue;
                     }
                 }
             }
         }
         //если не установлено интернет соединение
         catch (System.Net.WebException)
         { }
     }));
     loadRecipesThread.Start();
 }
Ejemplo n.º 20
0
        public static bool CanRecyclerViewScroll(RecyclerView view)
        {
            if (view == null || view.GetAdapter() == null || view.GetLayoutManager() == null)
                return false;
            RecyclerView.LayoutManager lm = view.GetLayoutManager();
            int count = view.GetAdapter().ItemCount;
            int lastVisible;

            if (lm is LinearLayoutManager)
            {
                LinearLayoutManager llm = (LinearLayoutManager)lm;
                lastVisible = llm.FindLastVisibleItemPosition();
            }
            else
            {
                throw new InvalidOperationException("Material Dialogs currently only supports LinearLayoutManager. Please report any new layout managers.");
            }

            if (lastVisible == -1)
                return false;

            bool lastItemVisible = lastVisible == count - 1;
            return !lastItemVisible ||
                    (view.ChildCount > 0 && view.GetChildAt(view.ChildCount - 1).Bottom > view.Height - view.PaddingBottom);
        }
        public void UpdateProductCatalogItem(int item, ProductListItem productListItem)
        {
            var adapter = recycler.GetAdapter() as ProductCatalogAdapter;

            adapter.NotifyItemChanged(item);
        }
 public bool CanDismiss (RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
 {
     var adapter = recyclerView.GetAdapter ();
     return adapter.GetItemViewType (viewHolder.LayoutPosition) == LogTimeEntriesAdapter.ViewTypeContent;
 }
Ejemplo n.º 23
0
 public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
 {
     recyclerView.GetAdapter().NotifyItemMoved(viewHolder.AdapterPosition, target.AdapterPosition);
     return(true);
 }
Ejemplo n.º 24
0
        public override void OnSwiped(AndroidX.RecyclerView.Widget.RecyclerView.ViewHolder viewHolder, int direction)
        {
            //Store the position in case of restoration.
            int position = viewHolder.LayoutPosition;

            //Store the potentially deleted item.
            ImageFileNameModel itemDeleted = null;

            if (direction == ItemTouchHelper.Right || direction == ItemTouchHelper.Left)
            {
                //Remove the item in the model.
                itemDeleted = ImageFileNameModels[position];

                ImageFileNameModels.RemoveAt(position);
                ItemCountHelper.UpdateExportItemsCount(mainActivity, ImageFileNameModels);
                RecyclerView.GetAdapter().NotifyItemRemoved(position);

                PermissionHelper.ShouldDelete = true;
            }

            if (itemDeleted != null)
            {
                //The item was actually deleted. Ask for restoration.

                string accentColor  = "#" + Fragment.Context.GetColor(Resource.Color.colorAccent).ToString("X");
                string primaryColor = "#" + Fragment.Context.GetColor(Resource.Color.colorPrimary).ToString("X");

                var snackBar = Snackbar.Make(Fragment.View, $"Item Removed", Snackbar.LengthLong)
                               .SetAction("Restore", (x) =>
                {
                    //Restore the item.
                    ImageFileNameModels.Insert(position, itemDeleted);
                    ItemCountHelper.UpdateExportItemsCount(mainActivity, ImageFileNameModels);
                    RecyclerView.GetAdapter().NotifyItemInserted(position);

                    mainActivity.SupportActionBar.Subtitle = $"Current count - {ImageFileNameModels.Count}";

                    PermissionHelper.ShouldDelete = false;
                })
                               .SetActionTextColor(Android.Graphics.Color.ParseColor(accentColor));

                snackBar.AddCallback(new FileDeletionCallback(itemDeleted.FileName, mainActivity, ImageFileNameModels));

                snackBar.View.SetBackgroundColor(Android.Graphics.Color.ParseColor(primaryColor));

                //Get the exisiting text.

                TextView textView = snackBar.View.FindViewById <TextView>(Resource.Id.snackbar_text);

                if (AppCompatDelegate.DefaultNightMode == AppCompatDelegate.ModeNightNo)
                {
                    textView.SetTextColor(Android.Graphics.Color.Black);
                }
                else
                {
                    textView.SetTextColor(Android.Graphics.Color.White);
                }

                snackBar.Show();
            }
        }
Ejemplo n.º 25
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.MainSearch);
            #region 界面下方的教室信息链表
            SearchRoom           searchRoom        = new SearchRoom(this);                                       //创建一个搜索类
            RecyclerView         RoomRecyclertView = FindViewById <RecyclerView>(Resource.Id.RoomRecyclertView); //绑定链表
            RecyclerView.Adapter roomlist_adapter  = new RecyclerViewAdapter(searchRoom.Show_Datas, this);       //创建适配器
            LoadMoreWrapper      loadMoreWrapper   = new LoadMoreWrapper(roomlist_adapter);                      //创建含有加载更多的适配器
            RoomRecyclertView.SetLayoutManager(new LinearLayoutManager(this));                                   //
            RoomRecyclertView.SetAdapter(loadMoreWrapper);                                                       //设置链表的适配器
            RoomRecyclertView.AddOnScrollListener(new Loadmore(this, searchRoom, loadMoreWrapper));              //设置滑动到底部时加载更多
            Detail DetailView = new Detail(this);                                                                //教室详细信息页面
            ((RecyclerViewAdapter)roomlist_adapter).OnClickEventHandler += (RoomNum) =>
            {                                                                                                    //点击教室后展开详细页面 传入教室相关信息
                foreach (var room in searchRoom.RoomList)
                {
                    if (room.RoomNum.Equals(RoomNum))
                    {
                        DetailView.ShowDetail(room);
                        break;
                    }
                }
            };
            #endregion
            #region 左菜单
            /*左菜单的toolbar呼出按钮*/
            DrawerLayout drawerLayout       = FindViewById <DrawerLayout>(Resource.Id.drawerLayout);
            Button       CalLeftMenu_button = FindViewById <Button>(Resource.Id.CalLeftMenu_button);
            CalLeftMenu_button.Click += (o, e) =>
            {
                drawerLayout.OpenDrawer((int)GravityFlags.Start);
            };
            //关于
            ImageView AboutimageView = FindViewById <ImageView>(Resource.Id.AboutimageView);
            TextView  AboutText      = FindViewById <TextView>(Resource.Id.AboutText);
            AboutimageView.Click += AboutimageView_Click;
            AboutText.Click      += AboutimageView_Click;
            void AboutimageView_Click(object sender, EventArgs e)
            {
                Intent intent = new Intent(this, typeof(AboutActivity));

                //启动关于界面
                intent.SetFlags(ActivityFlags.SingleTop);
                StartActivity(intent);
            }

            //吐槽
            ImageView TocaoimageView = FindViewById <ImageView>(Resource.Id.TocaoimageView);
            TextView  TocaoText      = FindViewById <TextView>(Resource.Id.TocaoText);
            TocaoimageView.Click += TocaoimageView_Click;
            TocaoText.Click      += TocaoimageView_Click;
            void TocaoimageView_Click(object sender, EventArgs e)
            {
                Intent intent = new Intent(this, typeof(TuCaoFakeActivity));

                //启动假吐槽界面
                intent.SetFlags(ActivityFlags.SingleTop);
                StartActivity(intent);
            }

            TocaoimageView.LongClick += TocaoimageView_LongClick;
            TocaoText.LongClick      += TocaoimageView_LongClick;
            void TocaoimageView_LongClick(object sender, View.LongClickEventArgs e)
            {
                Intent intent = new Intent(this, typeof(TuCaoActivity));

                //启动吐槽界面
                intent.SetFlags(ActivityFlags.SingleTop);
                StartActivity(intent);
            }

            /*左菜单的版本号*/
            TextView VersionCode = FindViewById <TextView>(Resource.Id.VersionCodeText);
            VersionCode.Text = "版本 " + APKVersionCodeUtils.GetVerName(this);
            #endregion
            #region 搜索条件
            conditions = new Condition(this, searchRoom, loadMoreWrapper);
            #endregion
            #region 搜索栏
            EditText SearchBox    = FindViewById <EditText>(Resource.Id.edit_search);
            Button   SearchButton = FindViewById <Button>(Resource.Id.SearchButton);
            /*搜索提示*/
            string  Tips    = GetString(Resource.String.Tip);
            JObject jObject = (JObject)JsonConvert.DeserializeObject(Tips);
            JArray  jArray  = (JArray)jObject["Tips"];
            Random  rd      = new Random();
            SearchBox.Hint = jArray[rd.Next(0, jArray.Count)].ToString();
            /*开始搜索教室*/
            /*第一次启动搜索一次防止说空*/
            loadMoreWrapper.LoadState = LoadMoreWrapper.LOADING;
            new LoadTask(this, searchRoom, loadMoreWrapper, conditions).Execute("101");
            SearchBox.EditorAction += (sender, args) =>
            {
                if (args.ActionId == ImeAction.Search)
                {
                    if (RoomRecyclertView.GetAdapter().ItemCount > 3)
                    {
                        RoomRecyclertView.ScrollToPosition(0);
                    }
                    searchRoom.Show_Datas.Clear();//清空显示数据
                    loadMoreWrapper.LoadState = LoadMoreWrapper.LOADING;
                    new LoadTask(this, searchRoom, loadMoreWrapper, conditions).Execute(SearchBox.Text);
                }
            };
            SearchButton.Click += (sender, args) =>
            {
                if (RoomRecyclertView.GetAdapter().ItemCount > 3)
                {
                    RoomRecyclertView.ScrollToPosition(0);
                }
                searchRoom.Show_Datas.Clear();//清空显示数据
                loadMoreWrapper.LoadState = LoadMoreWrapper.LOADING;
                new LoadTask(this, searchRoom, loadMoreWrapper, conditions).Execute(SearchBox.Text);
            };
            /*左右按钮换颜色*/
            AppBarLayout layout = FindViewById <AppBarLayout>(Resource.Id.appBarLayout1);
            layout.OffsetChanged += (object sender, AppBarLayout.OffsetChangedEventArgs e) =>
            {
                int gray = 255;
                if (-e.VerticalOffset + 162 < 255)
                {
                    gray = -e.VerticalOffset + 162;
                }
                Color filtercolor = Color.Rgb(255, 242, gray);
                CalLeftMenu_button.Background.SetColorFilter(filtercolor, PorterDuff.Mode.Multiply);
                SearchButton.Background.SetColorFilter(filtercolor, PorterDuff.Mode.Multiply);
            };
            #endregion
        }
Ejemplo n.º 26
0
        public bool OnInterceptTouchEvent(RecyclerView recyclerView, MotionEvent @event)
        {
            try
            {
                switch (@event.Action)
                {
                case MotionEventActions.Down:
                    lastX = (int)@event.GetX();
                    break;

                case MotionEventActions.Move:
                    bool isScrollingRight = @event.GetX() < lastX;
                    if (isScrollingRight && ((LinearLayoutManager)RecyclerView.GetLayoutManager()).FindLastCompletelyVisibleItemPosition() == RecyclerView.GetAdapter().ItemCount - 1 ||
                        !isScrollingRight && ((LinearLayoutManager)RecyclerView.GetLayoutManager()).FindFirstCompletelyVisibleItemPosition() == 0)
                    {
                        ViewPager.UserInputEnabled = true;
                    }
                    else
                    {
                        ViewPager.UserInputEnabled = false;
                    }
                    break;

                case MotionEventActions.Up:
                    lastX = 0;
                    ViewPager.UserInputEnabled = true;
                    break;
                }
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Ejemplo n.º 27
0
 public override void OnSaveInstanceState(Bundle outState)
 {
     base.OnSaveInstanceState(outState);
     ((ExpRecyclerViewAdapter)recyclerView.GetAdapter()).OnSaveInstanceState(outState);
 }
Ejemplo n.º 28
0
        public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            try
            {
                base.OnScrolled(recyclerView, dx, dy);

                var visibleItemCount = recyclerView.ChildCount;
                var totalItemCount   = recyclerView.GetAdapter().ItemCount;

                int pastVisibleItems;
                switch (LayoutManager)
                {
                case LinearLayoutManager managerLinear:
                    pastVisibleItems = managerLinear.FindFirstVisibleItemPosition();
                    break;

                default:
                    switch (LayoutManager)
                    {
                    case GridLayoutManager managerGrid:
                        pastVisibleItems = managerGrid.FindFirstVisibleItemPosition();
                        break;

                    case StaggeredGridLayoutManager managerStaggeredGrid:
                    {
                        int[] firstVisibleItemPositions = new int[SpanCount];
                        pastVisibleItems = managerStaggeredGrid.FindFirstVisibleItemPositions(firstVisibleItemPositions)[0];
                        break;
                    }

                    default:
                        pastVisibleItems = LayoutManager?.FindFirstVisibleItemPosition() ?? 0;
                        break;
                    }

                    break;
                }

                if (visibleItemCount + pastVisibleItems + 4 < totalItemCount)
                {
                    return;
                }

                switch (IsLoading)
                {
                //&& !recyclerView.CanScrollVertically(1)
                case true:
                    return;

                default:
                    //IsLoading = true;
                    LoadMoreEvent?.Invoke(this, null);

                    //if (visibleItemCount + pastVisibleItems + 8 >= totalItemCount)
                    //{
                    //    //Load More  from API Request
                    //    if (IsLoading == false)
                    //    {
                    //        LoadMoreEvent?.Invoke(this, null);
                    //        IsLoading = true;
                    //    }
                    //}
                    break;
                }
            }
            catch (Exception exception)
            {
                Methods.DisplayReportResultTrack(exception);
            }
        }
        public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
        {
            RecyclerView.LayoutManager layoutManager = parent.GetLayoutManager();
            if (!(layoutManager is GridLayoutManager))
            {
                outRect.Set(0, 0, 0, 0);
                return;
            }

            RecyclerView.Adapter adapter = parent.GetAdapter();
            if (adapter == null)
            {
                outRect.Set(0, 0, 0, 0);
                return;
            }

            int position = parent.GetChildLayoutPosition(view);

            if (position == -1)
            {
                outRect.Set(0, 0, 0, 0);
                return;
            }

            GridLayoutManager glm = (GridLayoutManager)layoutManager;
            int size      = adapter.ItemCount;
            int span      = glm.SpanCount;
            int spanIndex = position % span;
            int spanGroup = position / span;

            if (spanIndex == 0)
            {
                outRect.Left = margin;
            }
            else
            {
                outRect.Left = (margin + 1) / 2;
            }
            if (spanIndex == span - 1)
            {
                outRect.Right = margin;
            }
            else
            {
                outRect.Right = margin / 2;
            }
            if (spanGroup == 0)
            {
                outRect.Top = margin;
            }
            else
            {
                outRect.Top = (margin + 1) / 2;
            }
            if (spanGroup == (size - 1) / span)
            {
                outRect.Bottom = margin;
            }
            else
            {
                outRect.Bottom = margin / 2;
            }
        }
Ejemplo n.º 30
0
			public override void OnScrolled (RecyclerView recyclerView, int dx, int dy)
			{
				base.OnScrolled (recyclerView, dx, dy);

				var visibleItemCount = recyclerView.ChildCount;

				var totalItemCount = recyclerView.GetAdapter().ItemCount;
				var lastVisibleItem = ((LinearLayoutManager)recyclerView.GetLayoutManager()).FindLastCompletelyVisibleItemPosition();

				if ((lastVisibleItem+1) == totalItemCount) {
					LoadMoreEvent (this, null);
				}
			}
Ejemplo n.º 31
0
 private void UpdateScreen(object sender, EventArgs e)
 {
     _items.Clear();
     _items.AddRange(Vm.GetItems(_myDebts));
     _listView.GetAdapter().NotifyDataSetChanged();
 }
Ejemplo n.º 32
0
        public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            pref = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager)recyclerView.GetLayoutManager();
            int lastVisibleItem = linearLayoutManager.FindLastVisibleItemPosition();
            int totalItemCount  = recyclerView.GetAdapter().ItemCount;

            if (!IsLoading && totalItemCount <= (lastVisibleItem + visibleThreshold))
            {
                // End has been reached
                // Do something
                var currPrefPage = pref.GetString("CurrentPage", string.Empty);
                if (!String.IsNullOrEmpty(currPrefPage))
                {
                    if (Int32.Parse(currPrefPage) > 0)
                    {
                        currentPage++;
                    }
                    else
                    {
                        currentPage = 2;
                    }
                }
                else
                {
                    currentPage++;
                }
                var editor = pref.Edit();
                editor.PutString("CurrentPage", currentPage.ToString());
                editor.Apply();

                IsLoading = true;
                Task.Factory.StartNew(async() => {
                    try{
                        var newPostList = new List <Post>();
                        await WebClient.LoadPosts(newPostList, currentPage);


                        (recyclerView.GetAdapter() as PostViewAdapter)._Posts.AddRange(newPostList);
                        //recyclerView.GetAdapter().HasStableIds = true;

                        _messageShown = false;
                        Application.SynchronizationContext.Post(_ => { recyclerView.GetAdapter().NotifyDataSetChanged(); }, null);
                        //recyclerView.GetAdapter().NotifyItemRangeInserted(recyclerView.GetAdapter().ItemCount,newPostList.Count);
                    }catch (Exception ex) {
                        //Insights.Report(ex,new Dictionary<string,string>{{"Message",ex.Message}},Insights.Severity.Error);
                        var text = ex.Message;
                        if (!_messageShown)
                        {
                            Application.SynchronizationContext.Post(_ => {
                                Toast.MakeText(Application.Context, "При загрузке данных произошла ошибка", ToastLength.Short).Show();
                            }, null);
                            _messageShown = true;
                        }
                    }


                    IsLoading = false;
                });
            }
        }
Ejemplo n.º 33
0
        private void progressThroughHitWaypoints(List <LatLng> waypoints, RecyclerView recyclerView)
        {
            //Gets the current position
            LatLng currentPos = new LatLng(map.MyLocation.Latitude, map.MyLocation.Longitude);

            //Steps forward through all waypoints that are within 50 meters of the current location
            while (currentPos.DistanceTo(waypoints[currentStep]) < 50 && currentStep < recyclerView.GetAdapter().ItemCount)
            {
                stepRouteForward(recyclerView);
            }
        }
Ejemplo n.º 34
0
        public bool CanDismiss(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
        {
            var adapter = recyclerView.GetAdapter();

            return(adapter.GetItemViewType(viewHolder.LayoutPosition) == RecyclerCollectionDataAdapter <IHolder> .ViewTypeContent);
        }
        public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
        {
            int right = _space / 2;
            int left  = _space / 2;

            bool isViewEdgeLeft  = false;
            bool isViewEdgeRight = false;

            int viewPosition = parent.GetChildAdapterPosition(view);
            int viewCount    = parent.GetAdapter().ItemCount;

            if (parent.GetLayoutManager() is ResponsiveGridLayoutManager responsiveGridLayout)
            {
                int top    = _space / 2;
                int bottom = _space / 2;

                bool isAutoComputedItemWidth = responsiveGridLayout.IsAutoComputedItemWidth();

                int spanCount = responsiveGridLayout.SpanCount;
                isViewEdgeLeft = viewPosition % spanCount == 0;
                bool isViewEdgeTop = viewPosition < spanCount;
                isViewEdgeRight = viewPosition % spanCount == spanCount - 1;
                bool isViewEdgeBottom = viewPosition / spanCount == viewCount - 1 / spanCount;

                if (isViewEdgeTop)
                {
                    top = isAutoComputedItemWidth ? 0 : _topPadding;
                }

                if (isViewEdgeBottom)
                {
                    bottom = isAutoComputedItemWidth ? 0 : _bottomPadding;
                }

                bool isHorizontalEdge = isViewEdgeLeft || isViewEdgeRight;

                if (!responsiveGridLayout.TryGetItemWidth(out int itemWidth))
                {
                    base.GetItemOffsets(outRect, view, parent, state);
                    return;
                }

                int gridLeftPadding  = _leftPadding;
                int gridRightPadding = _rightPadding;
                if (spanCount == 1)
                {
                    // If there is only one column we want our items centered
                    gridLeftPadding  = 0;
                    gridRightPadding = 0;
                }

                //InternalLogger.Info(
                //    $"interSpacing computation:{Environment.NewLine}    parent.MeasuredWidth: {parent.MeasuredWidth}{Environment.NewLine}    parent.Width: {parent.Width}{Environment.NewLine}    spanCount: {spanCount}{Environment.NewLine}    itemWidth:{itemWidth}{Environment.NewLine}    gridLeftPadding: {gridLeftPadding}{Environment.NewLine}    gridRightPadding: {gridRightPadding}");

                int availableWidthSpace =
                    parent.MeasuredWidth - gridLeftPadding - gridRightPadding - spanCount * itemWidth;

                //InternalLogger.Info($"availableWidthSpace: {availableWidthSpace}");

                if (spanCount == 1)
                {
                    if (isAutoComputedItemWidth)
                    {
                        left  = 0;
                        right = 0;
                    }
                    else
                    {
                        left = right = availableWidthSpace / 2;
                    }
                }
                else
                {
                    int interItemSpace     = availableWidthSpace / (spanCount - 1);
                    int halfInterItemSpace = interItemSpace / 2;
                    left  = interItemSpace / 2;
                    right = interItemSpace / 2;

                    if (isHorizontalEdge)
                    {
                        int remaining = availableWidthSpace - halfInterItemSpace * 2 * (spanCount - 1);

                        // InternalLogger.Info($"halfInterItemSpace: {halfInterItemSpace}, remaining: {remaining}");

                        if (isViewEdgeLeft)
                        {
                            left = _leftPadding + remaining;
                        }

                        if (isViewEdgeRight)
                        {
                            right = _rightPadding;
                        }
                    }
                }

                if (isAutoComputedItemWidth)
                {
                    base.GetItemOffsets(outRect, view, parent, state);
                    outRect.Set(outRect.Left, top, outRect.Right, bottom);

                    // InternalLogger.Info(
                    //    $"view n°{viewPosition + 1} => left: {outRect.Left}, top: {outRect.Top}, right: {outRect.Right}, bottom: {outRect.Bottom}");
                    return;
                }

                outRect.Set(left, top, right, bottom);
                // InternalLogger.Info(
                //    $"view n°{viewPosition + 1} => left: {outRect.Left}, top: {outRect.Top}, right: {outRect.Right}, bottom: {outRect.Bottom}");
                return;
            }

            if (!(parent.GetLayoutManager() is LinearLayoutManager))
            {
                base.GetItemOffsets(outRect, view, parent, state);
                return;
            }

            isViewEdgeLeft  = viewPosition == 0;
            isViewEdgeRight = viewPosition == viewCount - 1;

            if (isViewEdgeLeft)
            {
                left = 0;
            }

            if (isViewEdgeRight)
            {
                right = 0;
            }

            outRect.Set(left, 0, right, 0);

            //InternalLogger.Info(
            //    $"view n°{viewPosition + 1} => left: {left}, right: {right}");
        }
		public override void OnScrolled (RecyclerView recyclerView, int dx, int dy)
		{

			base.OnScrolled (recyclerView, dx, dy);

			var visibleItemCount = recyclerView.ChildCount;
			//			Console.Error.WriteLine ("isRefeshing"+MySoal_Tab_1.isRefeshing);
			//
			if (MyHealth_Tab_2.isRefreshing) {
				Console.Error.WriteLine ("masuk");
				MyHealth_Tab_2.worker.CancelAsync ();

				if (MyHealth_Tab_2.worker.CancellationPending) { 
					if (MyHealth_Tab_2.worker.IsBusy == true)
					{

					}				
				}			
			}

			var totalItemCount = recyclerView.GetAdapter().ItemCount;
			var lastVisibleItem = ((LinearLayoutManager)recyclerView.GetLayoutManager()).FindLastCompletelyVisibleItemPosition();

			if ((lastVisibleItem+1) == totalItemCount) {
				Console.Error.WriteLine ("scrolll222");

				LoadMoreEvent (this, null);
			}
		}
Ejemplo n.º 37
0
 public bool CanDismiss (RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
 {
     var adapter = recyclerView.GetAdapter ();
     return adapter.GetItemViewType (viewHolder.LayoutPosition) == RecyclerCollectionDataAdapter<IHolder>.ViewTypeContent;
 }
        public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            try
            {
                base.OnScrolled(recyclerView, dx, dy);

                var visibleItemCount = recyclerView.ChildCount;
                var totalItemCount   = recyclerView.GetAdapter().ItemCount;

                if (LayoutManager == null)
                {
                    LayoutManager = (LinearLayoutManager)recyclerView.GetLayoutManager();
                }

                dynamic pastVisibleItems;
                switch (LayoutManager)
                {
                case GridLayoutManager managerGrid:
                    pastVisibleItems = managerGrid.FindFirstVisibleItemPosition();
                    break;

                case LinearLayoutManager managerLinear:
                    pastVisibleItems = managerLinear.FindFirstVisibleItemPosition();
                    break;

                case StaggeredGridLayoutManager managerStaggeredGrid:
                {
                    int[] firstVisibleItemPositions = new int[SpanCount];
                    pastVisibleItems = managerStaggeredGrid.FindFirstVisibleItemPositions(firstVisibleItemPositions)[0];
                    break;
                }

                default:
                    pastVisibleItems = LayoutManager.FindFirstVisibleItemPosition();
                    break;
                }

                if (visibleItemCount + pastVisibleItems + 4 < totalItemCount)
                {
                    return;
                }

                if (IsLoading /* && !recyclerView.CanScrollVertically(1)*/)
                {
                    return;
                }

                LoadMoreEvent?.Invoke(this, null);

                //if (visibleItemCount + pastVisibleItems + 8 >= totalItemCount)
                //{
                //    //Load More  from API Request
                //    if (IsLoading == false)
                //    {
                //        LoadMoreEvent?.Invoke(this, null);
                //        IsLoading = true;
                //    }
                //}
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Ejemplo n.º 39
0
        public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
        {
            var position = parent.GetChildAdapterPosition(view);
            var spanCount = 0;
            var orientation = 0;
            var spanIndex = 0;
            int headerCount = 0, footerCount = 0;

            var adapterObj  = parent.GetAdapter();
            var adapterType = adapterObj.GetType();

            if (adapterType.IsAssignableFrom(typeof(RecyclerArrayAdapter <>)))
            {
                headerCount = (int)adapterType.GetMethod("GetHeaderCount").Invoke(adapterObj, null);
                footerCount = (int)adapterType.GetMethod("GetFooterCount").Invoke(adapterObj, null);
            }

            var layoutManager = parent.GetLayoutManager();

            switch (layoutManager)
            {
            case StaggeredGridLayoutManager manager:
                orientation = manager.Orientation;
                spanCount   = manager.SpanCount;
                spanIndex   = ((StaggeredGridLayoutManager.LayoutParams)view.LayoutParameters).SpanIndex;
                break;

            case GridLayoutManager gridLayoutManager:
                orientation = gridLayoutManager.Orientation;
                spanCount   = gridLayoutManager.SpanCount;
                spanIndex   = ((GridLayoutManager.LayoutParams)view.LayoutParameters).SpanIndex;
                break;

            case LinearLayoutManager linearLayoutManager:
                orientation = linearLayoutManager.Orientation;
                spanCount   = 1;
                spanIndex   = 0;
                break;
            }

            //普通Item的尺寸
            if ((position >= headerCount && position < parent.GetAdapter().ItemCount - footerCount))
            {
                GravityFlags gravity;
                if (spanIndex == 0 && spanCount > 1)
                {
                    gravity = GravityFlags.Left;
                }
                else if (spanIndex == spanCount - 1 && spanCount > 1)
                {
                    gravity = GravityFlags.Right;
                }
                else if (spanCount == 1)
                {
                    gravity = GravityFlags.FillHorizontal;
                }
                else
                {
                    gravity = GravityFlags.Center;
                }
                if (orientation == OrientationHelper.Vertical)
                {
                    switch (gravity)
                    {
                    case GravityFlags.Left:
                        if (_paddingEdgeSide)
                        {
                            outRect.Left = _halfSpace * 2;
                        }
                        outRect.Right = _halfSpace;
                        break;

                    case GravityFlags.Right:
                        outRect.Left = _halfSpace;
                        if (_paddingEdgeSide)
                        {
                            outRect.Right = _halfSpace * 2;
                        }
                        break;

                    case GravityFlags.FillHorizontal:
                        if (_paddingEdgeSide)
                        {
                            outRect.Left  = _halfSpace * 2;
                            outRect.Right = _halfSpace * 2;
                        }
                        break;

                    case GravityFlags.Center:
                        outRect.Left  = _halfSpace;
                        outRect.Right = _halfSpace;
                        break;
                    }
                    if (position - headerCount < spanCount && _paddingStart)
                    {
                        outRect.Top = _halfSpace * 2;
                    }
                    outRect.Bottom = _halfSpace * 2;
                }
                else
                {
                    switch (gravity)
                    {
                    case GravityFlags.Left:
                        if (_paddingEdgeSide)
                        {
                            outRect.Bottom = _halfSpace * 2;
                        }
                        outRect.Top = _halfSpace;
                        break;

                    case GravityFlags.Right:
                        outRect.Bottom = _halfSpace;
                        if (_paddingEdgeSide)
                        {
                            outRect.Top = _halfSpace * 2;
                        }
                        break;

                    case GravityFlags.FillHorizontal:
                        if (_paddingEdgeSide)
                        {
                            outRect.Left  = _halfSpace * 2;
                            outRect.Right = _halfSpace * 2;
                        }
                        break;

                    case GravityFlags.Center:
                        outRect.Bottom = _halfSpace;
                        outRect.Top    = _halfSpace;
                        break;
                    }
                    if (position - headerCount < spanCount && _paddingStart)
                    {
                        outRect.Left = _halfSpace * 2;
                    }
                    outRect.Right = _halfSpace * 2;
                }
            }
            else
            {
                //只有HeaderFooter进到这里
                if (!_paddingHeaderFooter)
                {
                    return;
                }

                //并且需要padding Header&Footer
                if (orientation == OrientationHelper.Vertical)
                {
                    if (_paddingEdgeSide)
                    {
                        outRect.Left  = _halfSpace * 2;
                        outRect.Right = _halfSpace * 2;
                    }
                    outRect.Top = _halfSpace * 2;
                }
                else
                {
                    if (_paddingEdgeSide)
                    {
                        outRect.Top    = _halfSpace * 2;
                        outRect.Bottom = _halfSpace * 2;
                    }
                    outRect.Left = _halfSpace * 2;
                }
            }
        }