Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Self-Destructing Message Android App Self-Destruction Maintaining Scroll Position in a ListView

Issue Maintaining Scroll Position in a ListView

I followed the instructions in regards to maintaining the scroll position of a ListView. However, I noticed a difference in the behavior of pressing the "Back" button vs the "Parent Activity" button (the latter exists in the activity's top menu bar). Pressing the "Back" button correctly maintains the position in the ListView. However, pressing the "Parent Activity" button the the ImageViewerActivty seems to generate a new instance of the MainActivty class as the ListAdapter returns null and the adapter is regenerated.

Can someone explain why clicking the "Parent Activity" button behaves like this? I guess one possible explanation is that you could start the ImageViewerActivity class from an activity other than the defined parent activity (definied in the Manifest XML). As such, the app may just start a new parent activity.

I was able to overcome this issues by overriding the "onMenuItemSelected" of the ImageViewerActivity and placing a check to see if the MenuItem ID being selected is android.R.id.home. If it is, I tell the class to finish() and then return true. Otherwise, return the result of the super event. If there's a better way to handle this, please let me know.

I think this could be mentioned in the video or in the notes below it.

Thanks, Travis

1 Answer

Raghda Talaa't
Raghda Talaa't
2,944 Points

Finally i figured out how to solve this,

By adding this line: android:launchMode="singleTop" to the parent activity (which is "MainActivity" in this

case) in the AndroidManifest.xml

This is from the android developer site:

"if you navigate up to an activity on the current stack, the behavior is determined by the parent activity's launch mode. If the parent activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP), the parent is brought to the top of the stack, and its state is preserved."

Great fix!