Up navigation with RecycleView

88 Views Asked by At

I'd like to ask your opinions about the ways to solve the problem with Android Up navigation that I'm trying to solve. I have an activity (MainActivity) with RecycleView, showing a scrollable list of items, being fetched from an API. Each item has an onclick listener, which opens the item detail activity, like so:

Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("item", item);
context.startActivity(intent);

DetailActivity has the Up button, where the user can return to the previous activity. Here's the manifest for this activity:

<activity
    android:name=".DetailActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.Base"
    android:parentActivityName=".MainActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity" />
</activity>

And here's the problem: when I navigate to the parent activity, the scroll list is reset and is at the top. If I use the back button on the device, the list is preserved and the scroll position remains, but not when I click the Up button...

I realize that in order to restore the scroll list I'd have to keep the list of already loaded items somewhere, maybe pass it to the DetailActivity and back, but I'm not sure this is the best solution.. Is there a better, more elegant and native solution to preserve the scroll items and scroll position? I've read through Android documentation about the Up navigation, but couldn't find the answer...

2

There are 2 best solutions below

1
Bö macht Blau On BEST ANSWER

If pressing "BACK" is what looks good with your app, then simply catch the "UP"-event:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case android.R.id.home:
            // simulate the "BACK" key
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}
3
Alexandre Martin On

For my list, this is the way I save the index and the way I restore the RecyclerView at that index (at the top) :

// save index and top position
int index = mList.getFirstVisiblePosition();

View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());

// ...

// restore index and position
mList.setSelectionFromTop(index, top);

credit : ian (Stack Overflow)

Keeping a sublist of already loaded items would be too heavy for your app...