Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!