mukeshsoni
mukeshsoni

Reputation: 583

Scroll to top and then go back On Back Button Pressed in Recyclerview

I have a . When user press back i want recyclerview to scroll to top. And again if user click back button then go to previous activity.

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
    //    if(recyclerview == onFirstPosition){
    //      goBack; }
        onBackPressed();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}


@Override
public void onBackPressed() {
    RecyclerView.SmoothScroller smoothScroller = new 
LinearSmoothScroller(getApplicationContext()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
    };
    smoothScroller.setTargetPosition(0);
    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView
            .getLayoutManager();
    layoutManager.startSmoothScroll(smoothScroller);
}

Now i can scroll to top with this code but don't know how to go back if user is on first item.

Upvotes: 2

Views: 2215

Answers (2)

Priyank Patel
Priyank Patel

Reputation: 12372

Try using below code...

@Override
public void onBackPressed() {

    if(layoutManager.findFirstCompletelyVisibleItemPosition()==0) {
        super.onBackPressed();           
    }else {
        layoutManager.scrollToPositionWithOffset(0, 0);
    }
}

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69709

First way

You can use a boolean flag like below example

Take one boolean isFirstTime=true; variable

Try this

@Override
    public void onBackPressed() {

        if(isFirstTime){
            recyclerView.smoothScrollToPosition(0);
            isFirstTime=false;
        }else {
            super.onBackPressed();
        }
    }

Second way

Using LinearLayoutManager check that the visible item in your screen is first item or not

Example

@Override
    public void onBackPressed() {

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView
                .getLayoutManager();
        if(layoutManager.findFirstCompletelyVisibleItemPosition()==0){
            super.onBackPressed();
        }else {
            recyclerView.smoothScrollToPosition(0);
        }
    }

Upvotes: 3

Related Questions