Navigate up with RecycleView

I would like to know your opinion on ways to solve the Android Up navigation problem that I am trying to solve. I have a MainActivity with RecycleView showing a scrollable list of items that are retrieved from the API. Each element has an onclick listener, which opens the element detail activity, for example:

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

DetailActivity has an Up button where the user can return to the previous action. Here is 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 go to parent activity, the scroll list is reset and is at the top. If I use the back button on the device, the list is saved and the scroll position remains, but not when I press the up button ...

, -, , DetailActivity , , . , ? Android , ...

+4
2

"BACK", , "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);
}
+4

RecyclerView ():

// 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);

: ian ( )

...

0

Source: https://habr.com/ru/post/1688034/


All Articles