How to scroll gridview to position?

后端 未结 3 2030
挽巷
挽巷 2020-12-06 07:35

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

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 07:47

    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)
    

提交回复
热议问题