7

I have 30 images on grid view (3 images per row). If user select 20th image and go to next screen and come back then I want to focus to that position. I used following line to code, it works for first 8 rows but in last 2 row it is not scrolling. Please help.

gridview.setSelection(position);
gridview.requestFocusFromTouch();
gridview.setSelection(position);

Thanks

Monali
  • 1,966
  • 12
  • 39
  • 59

3 Answers3

14

The reason is because your view will be reused in your adapter.

public class ImageAdapter extends BaseAdapter {
    private Context context;
    private final String[] someprivatevariable;

    public ImageAdapter(Context context, String[] mobileValues) {
        // Your boring constructor
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

            // REUSE VIEW IF NOT NULL CODE
        if (convertView == null) {
                  .....
                  .....
                  you generally create your view here
        } else {
            gridView = (View) convertView;
        }

        return gridView;
    }
}

If your view is forced not to reuse then you can scrolltoposition by saving this value

int index = gridview.getFirstVisiblePosition(); 

and restore the value by

gridview.smoothScrollToPosition(int index)
Lalith B
  • 11,843
  • 6
  • 29
  • 47
  • @lalitab B but smoothScrollToPosition(index) is not working for ICS.Is there any way to use on ICS Please tell me thanks in Advance. – Hradesh Kumar Apr 01 '14 at 10:30
  • 1
    @Lalith B Do you know how to make a NOT smooth scroll? I have >1000 elements in my grid view and smoothScroll takes a while. – Agata May 20 '15 at 10:58
7

You can try somthing like this .I hope this will work for you..

When selection happens do this save position

int index = gridview.getFirstVisiblePosition();

And when you come back to the gridview then you can try this

gridview.smoothScrollToPosition(int index)
Sreedev
  • 6,563
  • 5
  • 43
  • 66
1

solution that worked for me was combine code from Monali and Sreedev (thank you Monali and Sreedev):

private int gridviewVerticalPositionWhenThumbnailTapped;

...

// save vertical position of gridview screen, will use to re-find this location if user follows a usre and gridview gets redrawn
gridviewVerticalPositionWhenThumbnailTapped = gridview.getFirstVisiblePosition();

later in app...

// scroll gridview to vertical position pre user tap follow                
gridview.setSelection(gridviewVerticalPositionWhenThumbnailTapped);
tmr
  • 1,500
  • 15
  • 22