0

I design an app that has 2 activity, first (all_activity) contains a listview using BaseAdapter. when a user clicks in one of the items it will start a new activity(Story_Detalies ) contains an information for the items in the listview.

I make the (all_activity) parent for the (Story_Detalies)activity and by using this code in (Story_Detalies) activity

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

it will show an arrow to go to the previous activity.

the listview has a lot of items so when a user clicks on the arrow I want the listview to be scrolled to the same point that it was previously.

And this is my code for listview in oncreate():-

    listView1 = (ListView) findViewById(R.id.lisallflashcard);
   adapter = new AdapterAllQ(getApplicationContext(), rows, prgmImages2,stortype);
   listView1.setAdapter(adapter);
Mi_Dhah
  • 396
  • 1
  • 6
  • 16
  • try this http://stackoverflow.com/questions/3014089/maintain-save-restore-scroll-position-when-returning-to-a-listview – D.J Jan 10 '17 at 04:14

1 Answers1

0

You can use getFirstVisiblePosition() to figure out which item is the first on screen. Next you can iterate over the children until you find the one corresponding to the first visible position, and use getTop() to figure out its vertical offset.

int position = listView.getFirstVisiblePosition();
int offset = 0;
for (int i = 0; i < listView.getChildCount(); i++) {
    View child = listView.getChildAt(i);
    if (listView.getPositionForView(child) == position) {
        offset = child.getTop();
        break;
    }
}

You can save those values and use them on the way back to call setSelectionFromTop(position offset).

Karakuri
  • 36,506
  • 12
  • 75
  • 103
  • I have this issue can't resolve method 'getPositionForChild(android.view.View)' – Mi_Dhah Jan 10 '17 at 02:12
  • @Mi_Dhah sorry, the method is `getPositionForView()`. I've updated the post accordingly. – Karakuri Jan 10 '17 at 04:07
  • Thank you for correction, just to make sure where is the right place to put your code a – Mi_Dhah Jan 10 '17 at 18:32
  • @Mi_Dhah Naturally it needs to be somewhere that you have access to the ListView and are aware of the appropriate points in the lifecycle where you want to use these methods. You will have to figure out the best way to integrate it. – Karakuri Jan 10 '17 at 20:24