简体   繁体   中英

How can I save the scroll position for my ListView

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM