Java Code Examples for androidx.recyclerview.widget.RecyclerView

The following examples show how to use androidx.recyclerview.widget.RecyclerView. These examples are extracted from open source projects. 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 Project: SAI   Source File: LicensesActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_licenses);

    RecyclerView recyclerView = findViewById(R.id.rv_licenses);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.getRecycledViewPool().setMaxRecycledViews(0, 16);

    LicensesAdapter adapter = new LicensesAdapter(this);
    recyclerView.setAdapter(adapter);

    LicensesViewModel viewModel = new ViewModelProvider(this).get(LicensesViewModel.class);
    viewModel.getLicenses().observe(this, adapter::setLicenses);
}
 
Example 2
@Override
protected void onContentViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onContentViewCreated(view, savedInstanceState);

    setTitle(R.string.installer_select_theme);
    getPositiveButton().setVisibility(View.GONE);
    getNegativeButton().setOnClickListener(v -> dismiss());

    RecyclerView recycler = (RecyclerView) view;
    recycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

    ThemeAdapter adapter = new ThemeAdapter(requireContext());
    adapter.setThemes(Theme.getInstance(requireContext()).getThemes());
    adapter.setOnThemeInteractionListener(this);
    mBillingManager.getDonationStatus().observe(this, adapter::setDonationStatus);
    recycler.setAdapter(adapter);

    revealBottomSheet();
}
 
Example 3
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    int position = parent.getChildAdapterPosition(view);
    int column = position % spanCount;

    if (includeEdge) {
        outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
        outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

        if (position < spanCount) {
            outRect.top = spacing;
        }
        outRect.bottom = spacing;
    } else {
        outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
        outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
        if (position >= spanCount) {
            outRect.top = spacing;
        }
    }
}
 
Example 4
Source Project: materialistic   Source File: ItemFragment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
    if (isNewInstance()) {
        mFragmentView = inflater.inflate(R.layout.fragment_item, container, false);
        mEmptyView = mFragmentView.findViewById(R.id.empty);
        mRecyclerView = (RecyclerView) mFragmentView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new SnappyLinearLayoutManager(getActivity(), true));
        mItemDecoration = new CommentItemDecoration(getActivity());
        mRecyclerView.addItemDecoration(mItemDecoration);
        mSwipeRefreshLayout = (SwipeRefreshLayout) mFragmentView.findViewById(R.id.swipe_layout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.white);
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.redA200);
        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            if (TextUtils.isEmpty(mItemId)) {
                return;
            }
            mCacheMode = ItemManager.MODE_NETWORK;
            if (mAdapter != null) {
                mAdapter.setCacheMode(mCacheMode);
            }
            loadKidData();
        });
    }
    return mFragmentView;
}
 
Example 5
Source Project: pandora   Source File: GridDividerDecoration.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isLastRow(RecyclerView parent, int pos, int spanCount,
                          int childCount) {
    RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
    if (layoutManager instanceof GridLayoutManager) {
        int lines = childCount % spanCount == 0 ? childCount / spanCount : childCount / spanCount + 1;
        return lines == pos / spanCount + 1;
    } else if (layoutManager instanceof StaggeredGridLayoutManager) {
        int orientation = ((StaggeredGridLayoutManager) layoutManager)
                .getOrientation();
        if (orientation == StaggeredGridLayoutManager.VERTICAL) {
            childCount = childCount - childCount % spanCount;
            if (pos >= childCount)
                return true;
        } else {
            if ((pos + 1) % spanCount == 0) {
                return true;
            }
        }
    }
    return false;
}
 
Example 6
private void drawVertical(Canvas canvas, RecyclerView parent) {
    final int top = parent.getPaddingTop();
    final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
    final int childSize = parent.getChildCount();
    for (int i = 0; i < childSize; i++) {
        final View child = parent.getChildAt(i);
        RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
        final int left = child.getRight() + layoutParams.rightMargin;
        final int right = left + space;
        if (mDivider != null) {
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
        if (mPaint != null) {
            canvas.drawRect(left, top, right, bottom, mPaint);
        }
    }
}
 
Example 7
Source Project: Pixiv-Shaft   Source File: ExpandCard.java    License: MIT License 6 votes vote down vote up
public void close() {
    if(isExpand){
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        layoutParams.height = maxHeight;
        for (int i = 0; i < getChildCount(); i++) {
            if (getChildAt(i) instanceof RecyclerView) {
                final RecyclerView recyclerView = ((RecyclerView) getChildAt(i));
                if (recyclerView.getLayoutManager() instanceof ScrollChange) {
                    ((ScrollChange) recyclerView.getLayoutManager()).setScrollEnabled(false);
                }
            }
        }
        setLayoutParams(layoutParams);
        isExpand = false;
    }
}
 
Example 8
Source Project: RecyclerExt   Source File: ReorderDecoration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    if (dragState == DragState.ENDED) {
        finishReorder(view);
        return;
    }

    int itemPosition = recyclerView.getChildAdapterPosition(view);
    if (itemPosition == selectedDragItemPosition) {
        view.setVisibility(View.INVISIBLE);
        return;
    }

    //Make sure the view is visible
    view.setVisibility(View.VISIBLE);

    //Calculate the new offsets
    updateFloatingItemCenter();
    setVerticalOffsets(view, itemPosition, floatingItemCenter, outRect);
    setHorizontalOffsets(view, itemPosition, floatingItemCenter, outRect);
}
 
Example 9
private RecyclerView.ViewHolder getItemViewHolder(final ViewGroup parent, final Section section) {
    View view;
    if (section.isItemViewWillBeProvided()) {
        view = section.getItemView(parent);
        if (view == null) {
            throw new NullPointerException("Section.getItemView() returned null");
        }
    } else {
        final Integer resId = section.getItemResourceId();
        if (resId == null) {
            throw new NullPointerException("Missing 'item' resource id");
        }
        view = inflate(resId, parent);
    }
    return section.getItemViewHolder(view);
}
 
Example 10
Source Project: BaldPhone   Source File: ScrollingHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onChanged() {
    if (child instanceof RecyclerView) {
        RecyclerView.Adapter<?> adapter = ((RecyclerView) child).getAdapter();
        if (adapter != null && emptyView != null) {
            if (adapter.getItemCount() == 0) {
                if (!gone)
                    setArrowsVisibility(false);
                if (emptyView instanceof TextView) {
                    ((TextView) emptyView).setText(empty);
                } else
                    emptyView.setVisibility(VISIBLE);
            } else {
                if (emptyView instanceof TextView) {
                    ((TextView) emptyView).setText("");
                } else
                    emptyView.setVisibility(INVISIBLE);
                if (!gone)
                    setArrowsVisibility(true);
            }
        }
    }

}
 
Example 11
Source Project: BaseProject   Source File: BaseQuickAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * add animation when you want to show time
 *
 * @param holder
 */
private void addAnimation(RecyclerView.ViewHolder holder) {
    if (mOpenAnimationEnable) {
        if (!mFirstOnlyEnable || holder.getLayoutPosition() > mLastPosition) {
            BaseAnimation animation = null;
            if (mCustomAnimation != null) {
                animation = mCustomAnimation;
            } else {
                animation = mSelectAnimation;
            }
            for (Animator anim : animation.getAnimators(holder.itemView)) {
                startAnim(anim, holder.getLayoutPosition());
            }
            mLastPosition = holder.getLayoutPosition();
        }
    }
}
 
Example 12
Source Project: NewFastFrame   Source File: StickyNavLayout.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
    final RecyclerView recyclerView = (RecyclerView) target;
    final View firstChild = recyclerView.getChildAt(0);
    final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
    Log.e("onNestedPreFling", "position:" + childAdapterPosition + "    x:" + firstChild.getY() + "");
    //不做拦截 可以传递给子View
    return false;
}
 
Example 13
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildPosition(childView));
        return true;
    }
    return false;
}
 
Example 14
@SuppressLint("RestrictedApi")
@Override
protected RecyclerView.Adapter onCreateAdapter(PreferenceScreen preferenceScreen) {
    return new PreferenceGroupAdapter(preferenceScreen) {
        @Override
        public void onPreferenceHierarchyChange(Preference preference) {
            if (preference != null)
                setAllPreferencesToAvoidHavingExtraSpace(preference);
            super.onPreferenceHierarchyChange(preference);
        }
    };
}
 
Example 15
Source Project: recyclerview-animators   Source File: ScaleInAnimator.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected void animateRemoveImpl(final RecyclerView.ViewHolder holder) {
  ViewCompat.animate(holder.itemView)
      .scaleX(0)
      .scaleY(0)
      .setDuration(getRemoveDuration())
      .setInterpolator(mInterpolator)
      .setListener(new DefaultRemoveVpaListener(holder))
      .setStartDelay(getRemoveDelay(holder))
      .start();
}
 
Example 16
Source Project: Telegram   Source File: JoinGroupAlert.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    JoinSheetUserCell cell = (JoinSheetUserCell) holder.itemView;
    if (position < chatInvite.participants.size()) {
        cell.setUser(chatInvite.participants.get(position));
    } else {
        int participants_count;
        if (chatInvite.chat != null) {
            participants_count = chatInvite.chat.participants_count;
        } else {
            participants_count = chatInvite.participants_count;
        }
        cell.setCount(participants_count - chatInvite.participants.size());
    }
}
 
Example 17
private void setUpRecyclerView() {
    ViewUtil.setUpFastScrollRecyclerViewColor(this, ((FastScrollRecyclerView) recyclerView), ThemeStore.accentColor(this));
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    if (playlist instanceof AbsCustomPlaylist) {
        adapter = new PlaylistSongAdapter(this, new ArrayList<>(), R.layout.item_list, false, this);
        recyclerView.setAdapter(adapter);
    } else {
        recyclerViewDragDropManager = new RecyclerViewDragDropManager();
        final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator();
        adapter = new OrderablePlaylistSongAdapter(this, new ArrayList<>(), R.layout.item_list, false, this, (fromPosition, toPosition) -> {
            if (PlaylistsUtil.moveItem(PlaylistDetailActivity.this, playlist.id, fromPosition, toPosition)) {
                Song song = adapter.getDataSet().remove(fromPosition);
                adapter.getDataSet().add(toPosition, song);
                adapter.notifyItemMoved(fromPosition, toPosition);
            }
        });
        wrappedAdapter = recyclerViewDragDropManager.createWrappedAdapter(adapter);

        recyclerView.setAdapter(wrappedAdapter);
        recyclerView.setItemAnimator(animator);

        recyclerViewDragDropManager.attachRecyclerView(recyclerView);
    }

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            checkIsEmpty();
        }
    });
}
 
Example 18
Source Project: FeatureAdapter   Source File: FeaturesAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting void validateNewViewItems(FeatureController<MODEL> controller, List<ViewItem> viewItems) {
  if (viewItems == null || viewItems.isEmpty()) {
    // null - there is no change in the controller to update
    // empty - this controller has no views
    return;
  }
  for (ViewItem viewItem : viewItems) {
    if(viewItem.viewType == RecyclerView.INVALID_TYPE) {
      String template = "The Model %s of a ViewItem is associated to a "
          + "ViewTypeDelegate that has not been "
          + "registered in the controller %s";
      throw new RuntimeException(String.format(template, viewItem.model, controller));
    }
  }
}
 
Example 19
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;
    switch (viewType) {
        case 0:
            view = new AttachButton(mContext);
            break;
        case 1:
        default:
            view = new AttachBotButton(mContext);
            break;
    }
    return new RecyclerListView.Holder(view);
}
 
Example 20
@Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
  super.onDetachedFromRecyclerView(recyclerView);
  for (int i = 0; i < getItemCount(); i++) {
    try {
      ((SearchResultItemView) getItem(i)).prepareToRecycle();
    } catch (NullPointerException | ClassCastException e) {
    }
  }
}
 
Example 21
Source Project: RecyclerViewHelper   Source File: LoadMoreWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // Get context
    this.mContext = parent.getContext();

    // Create view by the view type.
    if (viewType == TYPE_FOOTER) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_loading_footer, parent, false);
        return new LoadMoreViewHolder(view);
    } else {
        return mAdapter.onCreateViewHolder(parent, viewType);
    }
}
 
Example 22
Source Project: nextcloud-notes   Source File: ItemAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
    switch (getItemViewType(position)) {
        case TYPE_SECTION: {
            ((SectionViewHolder) holder).bind((SectionItem) itemList.get(position));
            break;
        }
        case TYPE_NOTE_WITH_EXCERPT:
        case TYPE_NOTE_WITHOUT_EXCERPT:
        case TYPE_NOTE_ONLY_TITLE: {
            ((NoteViewHolder) holder).bind((DBNote) itemList.get(position), showCategory, mainColor, textColor, searchQuery);
            break;
        }
    }
}
 
Example 23
Source Project: Telegram   Source File: PollCreateActivity.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void showQuizHint() {
    int count = listView.getChildCount();
    for (int a = answerStartRow; a < answerStartRow + answersCount; a++) {
        RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(a);
        if (holder != null && holder.itemView instanceof PollEditTextCell) {
            PollEditTextCell pollEditTextCell = (PollEditTextCell) holder.itemView;
            if (pollEditTextCell.getTop() > AndroidUtilities.dp(40)) {
                hintView.showForView(pollEditTextCell.getCheckBox(), true);
                break;
            }
        }
    }
}
 
Example 24
@Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  switch (viewType) {
    case REWARD_APP:
      return new RewardAppInBundleViewHolder(LayoutInflater.from(parent.getContext())
          .inflate(REWARD_APP, parent, false), appClickedEvents);
    case APP:
      return new AppInBundleViewHolder(LayoutInflater.from(parent.getContext())
          .inflate(APP, parent, false), appClickedEvents, oneDecimalFormatter);
    default:
      throw new IllegalArgumentException("Wrong type of App");
  }
}
 
Example 25
Source Project: monero-wallet-android-app   Source File: DividerItemDecoration.java    License: MIT License 5 votes vote down vote up
private void drawHorizontal(Canvas canvas, RecyclerView parent) {
    canvas.save();
    final int top;
    final int bottom;
    //noinspection AndroidLintNewApi - NewApi lint fails to handle overrides.
    if (parent.getClipToPadding()) {
        top = parent.getPaddingTop();
        bottom = parent.getHeight() - parent.getPaddingBottom();
        canvas.clipRect(parent.getPaddingLeft(), top,
                parent.getWidth() - parent.getPaddingRight(), bottom);
    } else {
        top = 0;
        bottom = parent.getHeight();
    }

    final int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        parent.getLayoutManager().getDecoratedBoundsWithMargins(child, mBounds);
        final int right = mBounds.right + Math.round(child.getTranslationX());
        final int left = right - mDividerSize;
        mDividerPaint.setColor(mDividerColor);
        mDividerPaint.setStyle(Paint.Style.FILL);
        canvas.drawRect(left + mMarginStart, top + mMarginTop, right - mMarginEnd, bottom - mMarginBottom, mDividerPaint);
    }
    canvas.restore();
}
 
Example 26
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case 0: {
            LanguageCell textSettingsCell = (LanguageCell) holder.itemView;
            LocaleController.LocaleInfo localeInfo;
            boolean last;
            if (search) {
                localeInfo = searchResult.get(position);
                last = position == searchResult.size() - 1;
            } else if (!unofficialLanguages.isEmpty() && position >= 0 && position < unofficialLanguages.size()) {
                localeInfo = unofficialLanguages.get(position);
                last = position == unofficialLanguages.size() - 1;
            } else {
                if (!unofficialLanguages.isEmpty()) {
                    position -= unofficialLanguages.size() + 1;
                }
                localeInfo = sortedLanguages.get(position);
                last = position == sortedLanguages.size() - 1;
            }
            if (localeInfo.isLocal()) {
                textSettingsCell.setLanguage(localeInfo, String.format("%1$s (%2$s)", localeInfo.name, LocaleController.getString("LanguageCustom", R.string.LanguageCustom)), !last);
            } else {
                textSettingsCell.setLanguage(localeInfo, null, !last);
            }
            textSettingsCell.setLanguageSelected(localeInfo == LocaleController.getInstance().getCurrentLocaleInfo());
            break;
        }
        case 1: {
            ShadowSectionCell sectionCell = (ShadowSectionCell) holder.itemView;
            if (!unofficialLanguages.isEmpty() && position == unofficialLanguages.size()) {
                sectionCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
            } else {
                sectionCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
            }
            break;
        }
    }
}
 
Example 27
Source Project: monero-wallet-android-app   Source File: WeSwipeHelper.java    License: MIT License 5 votes vote down vote up
private int checkHorizontalSwipe(RecyclerView.ViewHolder viewHolder, int flags) {
    if ((flags & (LEFT | RIGHT)) != 0) {
        final int dirFlag = mDx > 0 ? RIGHT : LEFT;
        if (mVelocityTracker != null && mActivePointerId > -1) {
            mVelocityTracker.computeCurrentVelocity(PIXELS_PER_SECOND,
                    mCallback.getSwipeVelocityThreshold(mMaxSwipeVelocity));
            final float xVelocity = mVelocityTracker.getXVelocity(mActivePointerId);
            final float yVelocity = mVelocityTracker.getYVelocity(mActivePointerId);
            final int velDirFlag = xVelocity > 0f ? RIGHT : LEFT;
            final float absXVelocity = Math.abs(xVelocity);
            if ((velDirFlag & flags) != 0 && dirFlag == velDirFlag
                    && absXVelocity >= mCallback.getSwipeEscapeVelocity(mSwipeEscapeVelocity)
                    && absXVelocity > Math.abs(yVelocity)) {
                return velDirFlag;
            }
        }
        int width = mRecyclerView.getWidth();
        //If the target layout follows the item view, the RecyclerView is wider than itself.
        if (swipeTypeIsFollowing()) {
            float swipeWidth = getSwipeWidth(viewHolder);
            width += (int) swipeWidth;
        }
        final float threshold = width * mCallback
                .getSwipeThreshold(viewHolder);
        if ((flags & dirFlag) != 0 && Math.abs(mDx) > threshold) {
            return dirFlag;
        }
    }
    return 0;
}
 
Example 28
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
    super.onViewRecycled(holder);

    int position = holder.getAdapterPosition();
    if (null == mReqAdapter || isHeaderView(position) || isFooterView(position)) {
        return;
    }

    mReqAdapter.onViewRecycled(holder);
}
 
Example 29
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
    if (holder instanceof UserListingRecyclerViewAdapter.DataViewHolder) {
        glide.clear(((UserListingRecyclerViewAdapter.DataViewHolder) holder).iconGifImageView);
        ((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.GONE);
    }
}
 
Example 30
Source Project: Bluefruit_LE_Connect_Android_V2   Source File: InfoFragment.java    License: MIT License 5 votes vote down vote up
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    final int resource = viewType == kViewType_Service ? R.layout.layout_info_service_item : viewType == kViewType_Characteristic ? R.layout.layout_info_characteristic_item : R.layout.layout_info_descriptor_item;
    View view = LayoutInflater.from(parent.getContext()).inflate(resource, parent, false);
    switch (viewType) {
        case kViewType_Characteristic:
            return new CharacteristicViewHolder(view);
        case kViewType_Descriptor:
            return new DescriptorViewHolder(view);
        default:
            return new ServiceViewHolder(view);
    }
}