androidandroid-scrollviewup-navigation

Up navigation with RecycleView


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...


Solution

  • 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);
    }