Android sets ListView to scroll to a certain position

Source: Internet
Author: User


Recently, when doing a project has a function is to click a button when the current page to stay in a fixed position, and the current page only a ListView, if it is scrollview, then believe it will be a lot simpler, direct call Scrollview.scrollto ( X,y) or Scrollview.smoothscrollto (X,y), one of these two methods, and then give the specified Y value OK, but if it is ListView, the principle is the same, there are two ways
SetSelection () and Setselectionfromtop ().

If you want to stay in the current 5th item position, that is, let the fifth item top, then direct listview.setselection (5) is OK, but if I want to stay in a more accurate position then I will call Setselectionfromtop () This method, such as I want to stay in the 4th and fifth item in the middle of the position, then assume the fourth item height is 100px, then direct Listview.setselectionfromtop (5,50) on the OK.


Explain the rationale of the two methods: the Setselectionfromtop () function is to set the ListView selected position and set an offset on the y-axis.

The SetSelection () method, passing in an index integer value, allows the ListView to position to the specified item.

Add a List1 and a Command1 to Form1 and add the following code. Press COMMAND1 button after running to see if it's the effect you want

/** Save the position **/
int currentposition = Listview.getfirstvisibleposition ();

Here u should save the currentposition anywhere

/** Restore the Previus saved position **/
Listview.setselection (savedposition);


Of course, you can also use this method:
Save index and top position
int index = mlist.getfirstvisibleposition ();
View v = mlist.getchildat (0);
int top = (v = = null)? 0:v.gettop ();

// ...

Restore
Mlist.setselectionfromtop (index, top);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.