简体   繁体   中英

Scrolling a ScrollView to a specific id

I have a Scrollview in my activity , I want when I press a button the view scrolls down to a specific ID in the view. After some search here I found I can use this code

scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
        }
    });

but it scrolls all the page down. I want to scroll to a specific ID in the middle of the view

ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
scrollView.postDelayed(new Runnable() {
     public void run() {
          scrollView.scrollTo(0, (int)view.getY());
     }
}, 100);

view = your view you want to scroll to

You can do this as below:

private void smartScrollToPosition(ListView listView, int desiredPosition) {
    //Write your logic here.
    listView.smoothScrollToPosition(desiredPosition);
}

On button handler you can call this as follows

ListView listView = (ListView) findViewById(R.id.lessonsListView);
smartScrollToPosition(listView, 0); // scroll to top
return true;

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