Java Code Examples for androidx.recyclerview.widget.RecyclerView#getAdapter()

The following examples show how to use androidx.recyclerview.widget.RecyclerView#getAdapter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DynamicLayoutUtils.java    From dynamic-support with Apache License 2.0 6 votes vote down vote up
/**
 * Sets full span for the positions in case of a {@link GridLayoutManager}.
 * This method must be called after setting an adapter for the recycler view.
 *
 * @param recyclerView The recycler view to set the span size.
 * @param positions The positions supported by the recycler view.
 * @param spanCount The maximum span supported by the layout manager.
 *
 * @see GridLayoutManager#setSpanSizeLookup(GridLayoutManager.SpanSizeLookup)
 */
public static void setFullSpanForPosition(@Nullable final RecyclerView recyclerView,
        @NonNull final Integer[] positions, int spanCount) {
    if (recyclerView == null || recyclerView.getAdapter() == null) {
        return;
    }

    if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
        final GridLayoutManager layoutManager =
                (GridLayoutManager) recyclerView.getLayoutManager();
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (Arrays.asList(positions).contains(position)) {
                    return Math.min(Math.abs(spanCount - position % spanCount), spanCount);
                } else {
                    return 1;
                }
            }
        });
    }
}
 
Example 2
Source File: Helper.java    From lbry-android with MIT License 6 votes vote down vote up
public static void refreshRecyclerView(RecyclerView rv) {
    if (rv == null) {
        return;
    }

    RecyclerView.Adapter adapter = rv.getAdapter();
    int prevScrollPosition = 0;

    RecyclerView.LayoutManager lm = rv.getLayoutManager();
    if (lm instanceof LinearLayoutManager) {
        prevScrollPosition = ((LinearLayoutManager) lm).findLastCompletelyVisibleItemPosition();
    } else if (lm instanceof GridLayoutManager) {
        prevScrollPosition = ((GridLayoutManager) lm).findLastCompletelyVisibleItemPosition();
    }

    rv.setAdapter(null);
    rv.setAdapter(adapter);
    rv.scrollToPosition(prevScrollPosition > 0 ? prevScrollPosition : 0);
}
 
Example 3
Source File: RecyclerViewItemRangeSelector.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
    boolean adapterIsEmpty = rv.getAdapter() == null || rv.getAdapter().getItemCount() == 0;
    boolean result = dragSelectActive && !adapterIsEmpty;

    if (result) {
        recyclerView = rv;

        if (hotspotHeight > -1) {
            hotspotTopBoundStart = hotspotOffsetTop;
            hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight;
            hotspotBottomBoundStart = rv.getMeasuredHeight() - hotspotHeight - hotspotOffsetBottom;
            hotspotBottomBoundEnd = rv.getMeasuredHeight() - hotspotOffsetBottom;
        }
    }

    if (result && e.getAction() == MotionEvent.ACTION_UP) {
        onDragSelectionStop();
    }
    return result;
}
 
Example 4
Source File: PreferenceFragment.java    From MaterialPreference with Apache License 2.0 6 votes vote down vote up
public final boolean shouldDrawDividerBelow(View view, RecyclerView parent) {
    if (!(parent.getAdapter() instanceof PreferenceGroupAdapter)) {
        return false;
    }
    PreferenceGroupAdapter adapter = (PreferenceGroupAdapter) parent.getAdapter();
    int index = parent.getChildAdapterPosition(view);
    if (index == RecyclerView.NO_POSITION) {
        return false;
    }
    Preference preference = adapter.getItem(index);
    switch (preference.getDividerBelowVisibility()) {
        case DividerVisibility.ENFORCED:
            return true;
        case DividerVisibility.FORBIDDEN:
            return false;
        case DividerVisibility.UNSPECIFIED:
        default:
            if (index == adapter.getItemCount() - 1) {
                return isAllowDividerAfterLastItem();
            }
            return shouldDrawDividerBelow(view, parent, adapter, index, preference);
    }
}
 
Example 5
Source File: BindingAdapters.java    From FirefoxReality with Mozilla Public License 2.0 5 votes vote down vote up
@BindingAdapter("items")
public static void bindAdapterWithDefaultBinder(@NonNull RecyclerView recyclerView, @Nullable ObservableList<Download> items) {
    DownloadsAdapter adapter = (DownloadsAdapter)recyclerView.getAdapter();
    if (adapter != null) {
        adapter.setDownloadsList(items);
    }
}
 
Example 6
Source File: ThemePreferenceTest.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    controller = Robolectric.buildActivity(PreferencesActivity.class,
            new Intent()
                    .putExtra(PreferencesActivity.EXTRA_TITLE, R.string.display)
                    .putExtra(PreferencesActivity.EXTRA_PREFERENCES, R.xml.preferences_display));
    activity = controller.create().start().resume().visible().get();
    RecyclerView list = activity.findViewById(android.R.id.list_container);
    list.setLayoutManager(new LinearLayoutManager(activity));
    RecyclerView.Adapter adapter = list.getAdapter();
    int position = ShadowSupportPreferenceManager
            .getPreferencePosition((PreferenceGroupAdapter) adapter, ThemePreference.class);
    RecyclerView.ViewHolder holder = CustomShadows.customShadowOf(adapter).getViewHolder(position);
    preferenceView = holder.itemView;
}
 
Example 7
Source File: MyItemDecoration.java    From RendererRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) {
	final RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

	final int itemPosition = parent.getChildAdapterPosition(view);
	if (itemPosition != RecyclerView.NO_POSITION) {
		if (layoutManager instanceof GridLayoutManager) {
			final RendererRecyclerViewAdapter adapter = (RendererRecyclerViewAdapter) parent.getAdapter();
			final ViewModel item = adapter.getItem(itemPosition);
			if (item instanceof RecyclerViewModel) {
				outRect.left = dpToPixels(-10);
				outRect.right = dpToPixels(-10);
				outRect.top = dpToPixels(5);
				outRect.bottom = dpToPixels(5);
			} else if (item instanceof CategoryModel) {
				outRect.left = dpToPixels(5);
				outRect.right = dpToPixels(5);
				outRect.top = dpToPixels(10);
				outRect.bottom = dpToPixels(2);
			} else {
				outRect.left = dpToPixels(5);
				outRect.right = dpToPixels(5);
				outRect.top = dpToPixels(5);
				outRect.bottom = dpToPixels(5);
			}
		} else {
			throw new UnsupportedClassVersionError("Unsupported LayoutManager");
		}
	}
}
 
Example 8
Source File: ReviewsBinding.java    From PopularMovies with MIT License 5 votes vote down vote up
@BindingAdapter("items")
public static void setItems(RecyclerView recyclerView, List<Review> items) {
    ReviewsAdapter adapter = (ReviewsAdapter) recyclerView.getAdapter();
    if (adapter != null) {
        adapter.submitList(items);
    }
}
 
Example 9
Source File: OmegaRecyclerView.java    From OmegaRecyclerView with MIT License 5 votes vote down vote up
protected int getAdapterPosition(RecyclerView parent, View view) {
    int childPosition = parent.getChildAdapterPosition(view);

    if (parent instanceof OmegaRecyclerView) {
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter instanceof HeaderFooterWrapperAdapter) {
            return ((HeaderFooterWrapperAdapter) adapter).applyChildPositionToRealPosition(childPosition);
        }
    }

    return childPosition;
}
 
Example 10
Source File: FontSizePreferenceTest.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    controller = Robolectric.buildActivity(PreferencesActivity.class,
            new Intent()
                    .putExtra(PreferencesActivity.EXTRA_TITLE, R.string.display)
                    .putExtra(PreferencesActivity.EXTRA_PREFERENCES, R.xml.preferences_display));
    activity = controller.create().postCreate(null).start().resume().visible().get();
    RecyclerView list = activity.findViewById(android.R.id.list_container);
    list.setLayoutManager(new LinearLayoutManager(activity));
    RecyclerView.Adapter adapter = list.getAdapter();
    int position = ShadowSupportPreferenceManager
            .getPreferencePosition((PreferenceGroupAdapter) adapter, FontSizePreference.class);
    RecyclerView.ViewHolder holder = CustomShadows.customShadowOf(adapter).getViewHolder(position);
    preferenceView = holder.itemView;
}
 
Example 11
Source File: MaterialDatePickerTestUtils.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Month findFirstVisibleItem(DialogFragment dialogFragment) {
  RecyclerView recyclerView =
      dialogFragment.getView().findViewWithTag(MaterialCalendar.MONTHS_VIEW_GROUP_TAG);
  MonthsPagerAdapter monthsPagerAdapter = (MonthsPagerAdapter) recyclerView.getAdapter();
  return monthsPagerAdapter.getPageMonth(
      ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition());
}
 
Example 12
Source File: CapturePictureUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 通过 RecyclerView 绘制为 Bitmap
 * <pre>
 *     不支持含 ItemDecoration 截图
 *     如果数据太多推荐 copy 代码, 修改为保存每个 Item Bitmap 到本地, 并在绘制时获取绘制
 * </pre>
 * @param recyclerView      {@link RecyclerView}
 * @param config            {@link Bitmap.Config}
 * @param verticalSpacing   每行之间的间隔 -
 * @param horizontalSpacing 每列之间的间隔 |
 * @return {@link Bitmap}
 */
public static Bitmap snapshotByRecyclerView(final RecyclerView recyclerView, final Bitmap.Config config,
                                            final int verticalSpacing, final int horizontalSpacing) {
    if (recyclerView == null || config == null) return null;
    try {
        // 获取适配器
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        // 获取布局管理器
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager != null && adapter != null) {
            // 判断布局类型
            if (layoutManager instanceof GridLayoutManager) {
                return snapshotByRecyclerView_GridLayoutManager(recyclerView,
                        config, verticalSpacing, horizontalSpacing);
            } else if (layoutManager instanceof LinearLayoutManager) {
                return snapshotByRecyclerView_LinearLayoutManager(recyclerView,
                        config, verticalSpacing, horizontalSpacing);
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                return snapshotByRecyclerView_StaggeredGridLayoutManager(recyclerView,
                        config, verticalSpacing, horizontalSpacing);
            }
            throw new Exception(String.format("Not Supported %s LayoutManager", layoutManager.getClass().getSimpleName()));
        } else {
            throw new Exception("Adapter or LayoutManager is Null");
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "snapshotByRecyclerView");
    }
    return null;
}
 
Example 13
Source File: HorizontalScrollCompat.java    From SmoothRefreshLayout with MIT License 5 votes vote down vote up
public static boolean canAutoLoadMore(View view) {
    if (ViewCatcherUtil.isRecyclerView(view)) {
        RecyclerView recyclerView = (RecyclerView) view;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager == null) {
            return false;
        }
        int lastVisiblePosition = 0;
        if (manager instanceof LinearLayoutManager) {
            LinearLayoutManager linearManager = ((LinearLayoutManager) manager);
            if (linearManager.getOrientation() != RecyclerView.HORIZONTAL) {
                return false;
            }
            lastVisiblePosition = linearManager.findLastVisibleItemPosition();
        } else if (manager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager gridLayoutManager = (StaggeredGridLayoutManager) manager;
            if (gridLayoutManager.getOrientation() != RecyclerView.HORIZONTAL) {
                return false;
            }
            int[] lastPositions = new int[gridLayoutManager.getSpanCount()];
            gridLayoutManager.findLastVisibleItemPositions(lastPositions);
            for (int value : lastPositions) {
                if (value > lastVisiblePosition) {
                    lastVisiblePosition = value;
                }
            }
        }
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        return adapter != null
                && adapter.getItemCount() > 0
                && lastVisiblePosition >= 0
                && lastVisiblePosition >= adapter.getItemCount() - 1;
    }
    return false;
}
 
Example 14
Source File: StickyHeaderLayoutManager.java    From StickyHeaders with MIT License 5 votes vote down vote up
@Override
public void onAttachedToWindow(RecyclerView view) {
	super.onAttachedToWindow(view);

	try {
		adapter = (SectioningAdapter) view.getAdapter();
	} catch (ClassCastException e) {
		throw new ClassCastException("StickyHeaderLayoutManager must be used with a RecyclerView where the adapter is a kind of SectioningAdapter");
	}
}
 
Example 15
Source File: HorizontalScrollCompat.java    From SmoothRefreshLayout with MIT License 5 votes vote down vote up
public static boolean canAutoRefresh(View view) {
    if (ViewCatcherUtil.isRecyclerView(view)) {
        RecyclerView recyclerView = (RecyclerView) view;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager == null) {
            return false;
        }
        int firstVisiblePosition = -1;
        if (manager instanceof LinearLayoutManager) {
            LinearLayoutManager linearManager = ((LinearLayoutManager) manager);
            if (linearManager.getOrientation() != RecyclerView.HORIZONTAL) {
                return false;
            }
            firstVisiblePosition = linearManager.findFirstVisibleItemPosition();
        } else if (manager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager gridLayoutManager = (StaggeredGridLayoutManager) manager;
            if (gridLayoutManager.getOrientation() != RecyclerView.HORIZONTAL) {
                return false;
            }
            int[] firstPositions = new int[gridLayoutManager.getSpanCount()];
            gridLayoutManager.findFirstVisibleItemPositions(firstPositions);
            for (int value : firstPositions) {
                if (value == 0) {
                    firstVisiblePosition = 0;
                    break;
                }
            }
        }
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        return adapter != null && firstVisiblePosition == 0;
    }
    return false;
}
 
Example 16
Source File: FastScrollerUtil.java    From MaterialScrollBar with Apache License 2.0 5 votes vote down vote up
public static void initHeaderScroller(RecyclerView rv)
{
    RecyclerView.Adapter adapter = rv.getAdapter();
    if(adapter instanceof IHeaderAdapter)
    {
        ((IHeaderAdapter) adapter).initScrollManager(getSpanSize(rv));
        initSpanSizeLookup(rv, (IHeaderAdapter)adapter);
    }
}
 
Example 17
Source File: FileViewFragment.java    From lbry-android with MIT License 5 votes vote down vote up
private void checkAndLoadRelatedContent() {
    View root = getView();
    if (root != null) {
        RecyclerView relatedContentList = root.findViewById(R.id.file_view_related_content_list);
        if (relatedContentList == null || relatedContentList.getAdapter() == null || relatedContentList.getAdapter().getItemCount() == 0) {
            loadRelatedContent();
        }
    }
}
 
Example 18
Source File: HistoryFragment.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
private ItemTouchHelper.Callback createTouchHelperCallback() {
    return new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT) {
        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        @Override
        public boolean isItemViewSwipeEnabled() {
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder from, RecyclerView.ViewHolder to) {
            HistoryAdapter adapter;
            if (recyclerView.getAdapter() instanceof HistoryAdapter) {
                adapter = (HistoryAdapter) recyclerView.getAdapter();
                adapter.swapItems(from.getAdapterPosition(), to.getAdapterPosition());
                return true;
            }

            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {

        }
    };
}
 
Example 19
Source File: RecyclerViewAttacher.java    From ScrollingPagerIndicator with Apache License 2.0 4 votes vote down vote up
@Override
public void attachToPager(@NonNull final ScrollingPagerIndicator indicator, @NonNull final RecyclerView pager) {
    if (!(pager.getLayoutManager() instanceof LinearLayoutManager)) {
        throw new IllegalStateException("Only LinearLayoutManager is supported");
    }
    if (pager.getAdapter() == null) {
        throw new IllegalStateException("RecyclerView has not Adapter attached");
    }
    this.layoutManager = (LinearLayoutManager) pager.getLayoutManager();
    this.recyclerView = pager;
    this.attachedAdapter = pager.getAdapter();
    this.indicator = indicator;

    dataObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            indicator.setDotCount(attachedAdapter.getItemCount());
            updateCurrentOffset();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            onChanged();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            onChanged();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            onChanged();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            onChanged();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            onChanged();
        }
    };
    attachedAdapter.registerAdapterDataObserver(dataObserver);
    indicator.setDotCount(attachedAdapter.getItemCount());
    updateCurrentOffset();

    scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE && isInIdleState()) {
                int newPosition = findCompletelyVisiblePosition();
                if (newPosition != RecyclerView.NO_POSITION) {
                    indicator.setDotCount(attachedAdapter.getItemCount());
                    if (newPosition < attachedAdapter.getItemCount()) {
                        indicator.setCurrentPosition(newPosition);
                    }
                }
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            updateCurrentOffset();
        }
    };

    recyclerView.addOnScrollListener(scrollListener);
}
 
Example 20
Source File: GridSectionAverageGapItemDecoration.java    From BaseRecyclerViewAdapterHelper with MIT License 4 votes vote down vote up
@Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getLayoutManager() instanceof GridLayoutManager && parent.getAdapter() instanceof BaseSectionQuickAdapter) {
            GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
            BaseSectionQuickAdapter<SectionEntity, BaseViewHolder> adapter = (BaseSectionQuickAdapter) parent.getAdapter();
            if (mAdapter != adapter) {
                setUpWithAdapter(adapter);
            }
            int spanCount = layoutManager.getSpanCount();
            int position = parent.getChildAdapterPosition(view) - mAdapter.getHeaderLayoutCount();
            SectionEntity entity = adapter.getItem(position);

            if (entity == null || entity.isHeader()) {
                //不处理header
                outRect.set(0, 0, 0, 0);
//                Log.w("GridAverageGapItem", "pos=" + position + "," + outRect.toShortString());
                return;
            }

            Section section = findSectionLastItemPos(position);

            if (gapHSizePx < 0 || gapVSizePx < 0) {
                transformGapDefinition(parent, spanCount);
            }
            outRect.top = gapVSizePx;
            outRect.bottom = 0;

            //下面的visualPos为单个Section内的视觉Pos
            int visualPos = position + 1 - section.startPos;
            if (visualPos % spanCount == 1) {
                //第一列
                outRect.left = sectionEdgeHPaddingPx;
                outRect.right = eachItemHPaddingPx - sectionEdgeHPaddingPx;
            } else if (visualPos % spanCount == 0) {
                //最后一列
                outRect.left = eachItemHPaddingPx - sectionEdgeHPaddingPx;
                outRect.right = sectionEdgeHPaddingPx;
            } else {
                outRect.left = gapHSizePx - (eachItemHPaddingPx - sectionEdgeHPaddingPx);
                outRect.right = eachItemHPaddingPx - outRect.left;
            }

            if (visualPos - spanCount <= 0) {
                //第一行
                outRect.top = sectionEdgeVPaddingPx;
            }

            if (isLastRow(visualPos, spanCount, section.getCount())) {
                //最后一行
                outRect.bottom = sectionEdgeVPaddingPx;
//                Log.w("GridAverageGapItem", "last row pos=" + position);
            }
//            Log.w("GridAverageGapItem", "pos=" + position + ",vPos=" + visualPos + "," + outRect.toShortString());
        } else {
            super.getItemOffsets(outRect, view, parent, state);
        }
    }