Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

android - How to scroll gridview to position?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...