Java Code Examples for android.support.v7.widget.RecyclerView#scrollToPosition()

The following examples show how to use android.support.v7.widget.RecyclerView#scrollToPosition() . 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: Utils.java    From smooth-app-bar-layout with Apache License 2.0 6 votes vote down vote up
public static boolean syncOffset(SmoothAppBarLayout smoothAppBarLayout, View target, int verticalOffset, View scroll) {
  boolean isSelected = target == scroll;
  if (scroll instanceof NestedScrollView) {
    NestedScrollView nestedScrollView = (NestedScrollView) scroll;
    if (nestedScrollView.getScrollY() < verticalOffset || (!isSelected && isScrollToTop(target))) {
      nestedScrollView.scrollTo(0, verticalOffset);
    }
    if (isSelected && (nestedScrollView.getScrollY() < verticalOffset || verticalOffset == 0)) {
      nestedScrollView.scrollTo(0, 0);
      smoothAppBarLayout.syncOffset(0);
    }
  } else if (scroll instanceof RecyclerView) {
    RecyclerView recyclerView = (RecyclerView) scroll;
    boolean isAccuracy = recyclerView.getLayoutManager().findViewByPosition(ObservableRecyclerView.HEADER_VIEW_POSITION) != null;
    if (isAccuracy && recyclerView.computeVerticalScrollOffset() < verticalOffset) {
      recyclerView.scrollBy(0, verticalOffset - recyclerView.computeVerticalScrollOffset());
    } else if (!isSelected && isScrollToTop(target)) {
      recyclerView.scrollToPosition(ObservableRecyclerView.HEADER_VIEW_POSITION);
    }
    if (isAccuracy && isSelected && (recyclerView.computeVerticalScrollOffset() < verticalOffset || verticalOffset == 0)) {
      recyclerView.scrollToPosition(ObservableRecyclerView.HEADER_VIEW_POSITION);
      smoothAppBarLayout.syncOffset(0);
    }
  }
  return true;
}
 
Example 2
Source File: Utils.java    From Expert-Android-Programming with MIT License 6 votes vote down vote up
public static boolean syncOffset(SmoothAppBarLayout smoothAppBarLayout, View target, int verticalOffset, View scroll) {
  boolean isSelected = target == scroll;
  if (scroll instanceof NestedScrollView) {
    NestedScrollView nestedScrollView = (NestedScrollView) scroll;
    if (nestedScrollView.getScrollY() < verticalOffset || (!isSelected && isScrollToTop(target))) {
      nestedScrollView.scrollTo(0, verticalOffset);
    }
    if (isSelected && (nestedScrollView.getScrollY() < verticalOffset || verticalOffset == 0)) {
      nestedScrollView.scrollTo(0, 0);
      smoothAppBarLayout.syncOffset(0);
    }
  } else if (scroll instanceof RecyclerView) {
    RecyclerView recyclerView = (RecyclerView) scroll;
    boolean isAccuracy = recyclerView.getLayoutManager().findViewByPosition(ObservableRecyclerView.HEADER_VIEW_POSITION) != null;
    if (isAccuracy && recyclerView.computeVerticalScrollOffset() < verticalOffset) {
      recyclerView.scrollBy(0, verticalOffset - recyclerView.computeVerticalScrollOffset());
    } else if (!isSelected && isScrollToTop(target)) {
      recyclerView.scrollToPosition(ObservableRecyclerView.HEADER_VIEW_POSITION);
    }
    if (isAccuracy && isSelected && (recyclerView.computeVerticalScrollOffset() < verticalOffset || verticalOffset == 0)) {
      recyclerView.scrollToPosition(ObservableRecyclerView.HEADER_VIEW_POSITION);
      smoothAppBarLayout.syncOffset(0);
    }
  }
  return true;
}
 
Example 3
Source File: ItemTouchHelper.java    From letv with Apache License 2.0 6 votes vote down vote up
public void onMoved(RecyclerView recyclerView, ViewHolder viewHolder, int fromPos, ViewHolder target, int toPos, int x, int y) {
    LayoutManager layoutManager = recyclerView.getLayoutManager();
    if (layoutManager instanceof ViewDropHandler) {
        ((ViewDropHandler) layoutManager).prepareForDrop(viewHolder.itemView, target.itemView, x, y);
        return;
    }
    if (layoutManager.canScrollHorizontally()) {
        if (layoutManager.getDecoratedLeft(target.itemView) <= recyclerView.getPaddingLeft()) {
            recyclerView.scrollToPosition(toPos);
        }
        if (layoutManager.getDecoratedRight(target.itemView) >= recyclerView.getWidth() - recyclerView.getPaddingRight()) {
            recyclerView.scrollToPosition(toPos);
        }
    }
    if (layoutManager.canScrollVertically()) {
        if (layoutManager.getDecoratedTop(target.itemView) <= recyclerView.getPaddingTop()) {
            recyclerView.scrollToPosition(toPos);
        }
        if (layoutManager.getDecoratedBottom(target.itemView) >= recyclerView.getHeight() - recyclerView.getPaddingBottom()) {
            recyclerView.scrollToPosition(toPos);
        }
    }
}
 
Example 4
Source File: ItemDragHelper.java    From MultiItem with Apache License 2.0 6 votes vote down vote up
/**
     * 当item位置变换,滚动recycler到正确的位置
     * TODO: 2017/2/21 0021 整理更优雅的写法  还有scrollToPosition(0)是否必要?
     */
    private void scrollToRightPositionWhenItemChanged(RecyclerView recyclerView, View itemView, int itemPos) {
        final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof ItemTouchHelper.ViewDropHandler) {
            OrientationHelper helper = OrientationHelper.createVerticalHelper(layoutManager);
            int start = helper.getDecoratedStart(itemView);
            int end = helper.getDecoratedEnd(itemView);
            ((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(
                    itemPos, lastItemPos > itemPos ? start : end - itemViewHeight);
//                System.out.println(lastItemPos + "-" + childPos + "OrientationHelperOrientationHelper:"
//                        + height + "==" + itemViewHeight + "=||=" + start + "===" + end + "||||||" + myStart + "===" + itemTargetView.getHeight() );
        }
        if (lastItemPos == 0 || itemPos == 0) {
            recyclerView.scrollToPosition(0);
        }
    }
 
Example 5
Source File: LocalMusicFragment.java    From YCAudioPlayer with Apache License 2.0 5 votes vote down vote up
public void onRefresh() {
    RecyclerView mRecyclerView = recyclerView.getRecyclerView();
    int firstVisibleItemPosition = ((LinearLayoutManager)
            mRecyclerView.getLayoutManager()).findFirstVisibleItemPosition();
    if (firstVisibleItemPosition == 0) {
        onLazyLoad();
        return;
    }
    mRecyclerView.scrollToPosition(5);
    mRecyclerView.smoothScrollToPosition(0);
}
 
Example 6
Source File: TangramEngine.java    From Tangram-Android with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void scrollToPosition(BaseCell cell) {
    if (cell != null) {
        int pos = mGroupBasicAdapter.getComponents().indexOf(cell);
        if (pos > 0) {
            RecyclerView recyclerView = getContentView();
            if (recyclerView != null) {
                recyclerView.scrollToPosition(pos);
            }
        }
    }
}
 
Example 7
Source File: TangramEngine.java    From Tangram-Android with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void scrollToPosition(Card card) {
    List<BaseCell> cells = card.getCells();
    if (cells.size() > 0) {
        BaseCell cell = cells.get(0);
        int pos = mGroupBasicAdapter.getComponents().indexOf(cell);
        if (pos > 0) {
            RecyclerView recyclerView = getContentView();
            if (recyclerView != null) {
                recyclerView.scrollToPosition(pos);
            }
        }
    }
}
 
Example 8
Source File: RecyclerViewAdapter.java    From NoListAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public void hideErrorView(RecyclerView recyclerView) {
    if (errorViewBinder == null && !isErrorViewShowing())
        return;
    errorViewBinder.showNow = false;
    notifyDataSetChanged();
    recyclerView.scrollToPosition(0);
}
 
Example 9
Source File: TangramEngine.java    From Tangram-Android with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void scrollToPosition(Card card) {
    List<BaseCell> cells = card.getCells();
    if (cells.size() > 0) {
        BaseCell cell = cells.get(0);
        int pos = mGroupBasicAdapter.getComponents().indexOf(cell);
        if (pos > 0) {
            RecyclerView recyclerView = getContentView();
            if (recyclerView != null) {
                recyclerView.scrollToPosition(pos);
            }
        }
    }
}
 
Example 10
Source File: DemoTwoRecyclerViewActivity.java    From TvWidget with Apache License 2.0 5 votes vote down vote up
private void createData(RecyclerView recyclerView,int id) {
    //创建数据集
    String[] dataset = new String[100];
    for (int i = 0; i < dataset.length; i++) {
        dataset[i] = "item" + i;
    }
    // 创建Adapter,并指定数据集
    MyAdapter adapter = new MyAdapter(this, dataset,id);
    // 设置Adapter
    recyclerView.setAdapter(adapter);
    recyclerView.scrollToPosition(0);
}
 
Example 11
Source File: RecyclerViewAdapter.java    From NoListAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public void showErrorView(RecyclerView recyclerView) {
    if (errorViewBinder == null || isErrorViewShowing())
        return;
    errorViewBinder.showNow = true;
    notifyDataSetChanged();
    recyclerView.scrollToPosition(0);
}
 
Example 12
Source File: EndlessStaggeredGridLayoutActivity.java    From HeaderAndFooterRecyclerView with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sample_activity);

    mRecyclerView = (RecyclerView) findViewById(R.id.list);

    //init data
    ArrayList<String> dataList = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        dataList.add("item" + i);
    }

    mCurrentCounter = dataList.size();

    mDataAdapter = new DataAdapter(this);
    mDataAdapter.addAll(dataList);

    mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mDataAdapter);
    mRecyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);

    //setLayoutManager
    ExStaggeredGridLayoutManager manager = new ExStaggeredGridLayoutManager (2, StaggeredGridLayoutManager.VERTICAL);
    manager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) mRecyclerView.getAdapter(), manager.getSpanCount()));
    mRecyclerView.setLayoutManager(manager);

    RecyclerViewUtils.setHeaderView(mRecyclerView, new SampleHeader(this));

    RecyclerViewStateUtils.setFooterViewState(EndlessStaggeredGridLayoutActivity.this, mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Normal, null);
    mRecyclerView.addOnScrollListener(mOnScrollListener);
    mRecyclerView.scrollToPosition(0);
}
 
Example 13
Source File: PreviewActivity.java    From imsdk-android with MIT License 5 votes vote down vote up
private void initRecyclerView() {
    rvPhotos = (RecyclerView) findViewById(R.id.rv_photos);
    adapter = new PreviewPhotosAdapter(this, photos, this);
    lm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    rvPhotos.setLayoutManager(lm);
    rvPhotos.setAdapter(adapter);
    rvPhotos.scrollToPosition(index);
    toggleSelector();
    snapHelper = new PagerSnapHelper();
    snapHelper.attachToRecyclerView(rvPhotos);
    rvPhotos.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

            View view = snapHelper.findSnapView(lm);
            if (view == null) {
                return;
            }
            int position = lm.getPosition(view);
            if (lastPosition == position) {
                return;
            }
            lastPosition = position;
            previewFragment.setSelectedPosition(-1);
            tvNumber.setText(getString(R.string.preview_current_number_easy_photos, lastPosition + 1, photos.size()));
            toggleSelector();
            PreviewPhotosAdapter.PreviewPhotosViewHolder holder = (PreviewPhotosAdapter.PreviewPhotosViewHolder) rvPhotos.getChildViewHolder(view);
            if (holder == null || holder.ivPhoto == null) {
                return;
            }
            if (holder.ivPhoto.getScale() != 1f) {
                holder.ivPhoto.setScale(1f, true);


            }
        }
    });
    tvNumber.setText(getString(R.string.preview_current_number_easy_photos, index + 1, photos.size()));
}
 
Example 14
Source File: TestUtils.java    From Awesome-WanAndroid with Apache License 2.0 4 votes vote down vote up
public void perform(UiController uiController, View view) {
    RecyclerView recyclerView = (RecyclerView) view;
    recyclerView.scrollToPosition(this.position);
}
 
Example 15
Source File: MoonPhasesView1.java    From SuntimesWidget with GNU General Public License v3.0 4 votes vote down vote up
private void init(Context context, AttributeSet attrs)
{
    initLocale(context);
    LayoutInflater.from(context).inflate(R.layout.layout_view_moonphases1, this, true);

    if (attrs != null)
    {
        LayoutParams lp = generateLayoutParams(attrs);
        centered = ((lp.gravity == Gravity.CENTER) || (lp.gravity == Gravity.CENTER_HORIZONTAL));
    }

    empty = (TextView)findViewById(R.id.txt_empty);
    card_view = (RecyclerView)findViewById(R.id.moonphases_card);

    card_layout = new LinearLayoutManager(context);
    card_layout.setOrientation(LinearLayoutManager.HORIZONTAL);

    card_view.setHasFixedSize(true);
    card_view.setItemViewCacheSize(7);
    card_view.setLayoutManager(card_layout);

    card_adapter = new PhaseAdapter(context);
    card_adapter.setItemWidth(Resources.getSystem().getDisplayMetrics().widthPixels / 4);  // initial width; reassigned later in onSizeChanged

    card_view.setAdapter(card_adapter);
    card_view.scrollToPosition(PhaseAdapter.CENTER_POSITION);

    GravitySnapHelper snapHelper = new GravitySnapHelper(Gravity.START); // new LinearSnapHelper();
    snapHelper.attachToRecyclerView(card_view);

    //card_scroller = new CardAdapter.CardViewScroller(context);
    //card_view.setOnScrollListener(onCardScrollListener);

    forwardButton = (ImageButton)findViewById(R.id.info_time_nextbtn);
    forwardButton.setOnClickListener(onResetClick1);
    forwardButton.setVisibility(GONE);

    backButton = (ImageButton)findViewById(R.id.info_time_prevbtn);
    backButton.setOnClickListener(onResetClick0);
    backButton.setVisibility(VISIBLE);
    backButton.postDelayed(new Runnable() {
        @Override
        public void run() {
            int position = card_layout.findFirstVisibleItemPosition();
            if (position == PhaseAdapter.CENTER_POSITION) {
                ViewUtils.fadeOutButton(backButton, ViewUtils.ANIM_VERYLONG);
            }
        }
    }, 1200);

    card_view.setOnScrollListener(onScrollChanged);

    initTheme(context);
    if (isInEditMode()) {
        updateViews(context);
    }
}
 
Example 16
Source File: FragmentMediaPlayer.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void initComponent(final View view) {

        final ImageView img_MusicImage = (ImageView) view.findViewById(R.id.ml_img_music_picture);
        onSetImage = new OnSetImage() {
            @Override
            public void setImage() {
                img_MusicImage.setImageBitmap(MusicPlayer.mediaThumpnail);
            }
        };

        musicSeekbar = view.findViewById(R.id.ml_seekBar1);
        musicSeekbar.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    MusicPlayer.setMusicProgress(musicSeekbar.getProgress());
                }
                return false;
            }
        });


        onBackFragment = new OnBackFragment() {
            @Override
            public void onBack() {
                removeFromBaseFragment();
            }
        };

        rcvListMusicPlayer = (RecyclerView) view.findViewById(R.id.rcvListMusicPlayer);
        final SlidingUpPanelLayout slidingUpPanelLayout = (SlidingUpPanelLayout) view.findViewById(R.id.sliding_layout);

        footerAdapter = new ItemAdapter<>();
        fastItemAdapter = new FastItemAdapter();
        fastItemAdapter.addAdapter(1, footerAdapter);

        rcvListMusicPlayer.setAdapter(fastItemAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
        rcvListMusicPlayer.setLayoutManager(linearLayoutManager);
        rcvListMusicPlayer.setHasFixedSize(true);

        rcvListMusicPlayer.addOnScrollListener(new EndlessRecyclerOnScrollListener(footerAdapter) {
            @Override
            public void onLoadMore(int currentPage) {
                footerAdapter.clear();
                footerAdapter.add(new ProgressItem().withEnabled(false));
                // Load your items here and add it to FastAdapter

                if (isThereAnyMoreItemToLoad) {
                    getInfoRealm();
                }
            }
        });


//        getDataFromServer(ProtoClientSearchRoomHistory.ClientSearchRoomHistory.Filter.AUDIO);
        loadLocalData(ProtoClientSearchRoomHistory.ClientSearchRoomHistory.Filter.AUDIO, ProtoGlobal.RoomMessageType.AUDIO);
        mediaList = new ArrayList<>();

        for (RealmRoomMessage r : MusicPlayer.mediaList) {
            if (r.isValid()) {
                fastItemAdapter.add(new AdapterListMusicPlayer().setItem(r).withIdentifier(r.getMessageId()));
            }
        }
        rcvListMusicPlayer.scrollToPosition(fastItemAdapter.getPosition(Long.parseLong(MusicPlayer.messageId)));
    }
 
Example 17
Source File: FastScrollToTop.java    From RecyclerViewTools with Apache License 2.0 4 votes vote down vote up
@Override public void run() {
   RecyclerView recyclerView = weakRecycler.get();
   if (recyclerView == null) return;
   recyclerView.scrollToPosition(lastScroll);
   recyclerView.smoothScrollToPosition(0);
}
 
Example 18
Source File: RecyclerViewStateUtils.java    From HeaderAndFooterRecyclerView with Apache License 2.0 4 votes vote down vote up
/**
 * 设置headerAndFooterAdapter的FooterView State
 *
 * @param instance      context
 * @param recyclerView  recyclerView
 * @param pageSize      分页展示时,recyclerView每一页的数量
 * @param state         FooterView State
 * @param errorListener FooterView处于Error状态时的点击事件
 */
public static void setFooterViewState(Activity instance, RecyclerView recyclerView, int pageSize, LoadingFooter.State state, View.OnClickListener errorListener) {

    if(instance==null || instance.isFinishing()) {
        return;
    }

    RecyclerView.Adapter outerAdapter = recyclerView.getAdapter();

    if (outerAdapter == null || !(outerAdapter instanceof HeaderAndFooterRecyclerViewAdapter)) {
        return;
    }

    HeaderAndFooterRecyclerViewAdapter headerAndFooterAdapter = (HeaderAndFooterRecyclerViewAdapter) outerAdapter;

    //只有一页的时候,就别加什么FooterView了
    if (headerAndFooterAdapter.getInnerAdapter().getItemCount() < pageSize) {
        return;
    }

    LoadingFooter footerView;

    //已经有footerView了
    if (headerAndFooterAdapter.getFooterViewsCount() > 0) {
        footerView = (LoadingFooter) headerAndFooterAdapter.getFooterView();
        footerView.setState(state);

        if (state == LoadingFooter.State.NetWorkError) {
            footerView.setOnClickListener(errorListener);
        }
        recyclerView.scrollToPosition(headerAndFooterAdapter.getItemCount() - 1);
    } else {
        footerView = new LoadingFooter(instance);
        footerView.setState(state);

        if (state == LoadingFooter.State.NetWorkError) {
            footerView.setOnClickListener(errorListener);
        }

        headerAndFooterAdapter.addFooterView(footerView);
        recyclerView.scrollToPosition(headerAndFooterAdapter.getItemCount() - 1);
    }
}
 
Example 19
Source File: TestUtils.java    From Scoops with Apache License 2.0 4 votes vote down vote up
public void perform(UiController uiController, View view) {
    RecyclerView recyclerView = (RecyclerView) view;
    recyclerView.scrollToPosition(this.position);
}
 
Example 20
Source File: MoonApsisView.java    From SuntimesWidget with GNU General Public License v3.0 4 votes vote down vote up
private void init(Context context, AttributeSet attrs)
{
    SuntimesUtils.initDisplayStrings(context);
    LayoutInflater.from(context).inflate(R.layout.layout_view_moonapsis, this, true);
    content = (LinearLayout)findViewById(R.id.moonapsis_layout);

    card_layout = new LinearLayoutManager(context);
    card_layout.setOrientation(LinearLayoutManager.HORIZONTAL);

    card_view = (RecyclerView)findViewById(R.id.moonapsis_card);
    card_view.setHasFixedSize(true);
    card_view.setItemViewCacheSize(7);
    card_view.setLayoutManager(card_layout);

    card_adapter = new MoonApsisAdapter(context);
    card_adapter.setItemWidth(Resources.getSystem().getDisplayMetrics().widthPixels / 3);  // initial width; 3 to screen; reassigned later in onSizeChanged

    card_view.setAdapter(card_adapter);
    card_view.scrollToPosition(MoonApsisAdapter.CENTER_POSITION);

    GravitySnapHelper snapHelper = new GravitySnapHelper(Gravity.START); // new LinearSnapHelper();
    snapHelper.attachToRecyclerView(card_view);

    forwardButton = (ImageButton)findViewById(R.id.info_time_nextbtn);
    forwardButton.setOnClickListener(onResetClick1);
    forwardButton.setVisibility(GONE);

    backButton = (ImageButton)findViewById(R.id.info_time_prevbtn);
    backButton.setOnClickListener(onResetClick0);
    backButton.setVisibility(VISIBLE);
    backButton.postDelayed(new Runnable() {
        @Override
        public void run() {
            int position = card_layout.findFirstVisibleItemPosition();
            if (position == MoonApsisAdapter.CENTER_POSITION) {
                ViewUtils.fadeOutButton(backButton, ViewUtils.ANIM_VERYLONG);
            }
        }
    }, 1200);

    card_view.setOnScrollListener(onScrollChanged);

    initTheme(context);
    if (isInEditMode()) {
        updateViews(context);
    }
}