5

I want to scroll my listview by pressing the buttons. Am using two buttons up and down and when i press up button the listview should move one row up and when i press down button the listview should move one row down.

My listview is based on this link. I found a good example of scrollview here. Now my question is instead of scrollview i need to use my listview and it should increase/decrease by one row. As am new to android anyone help me in solving this issue. Thanks in advance.

Community
  • 1
  • 1
AndroidOptimist
  • 1,419
  • 3
  • 23
  • 38

3 Answers3

3

You can try either of the following:

For a direct scroll:

getListView().setSelection(int);

For a smooth scroll:

getListView().smoothScrollToPosition(int);

Sample Code:

public View.OnClickListener onChk = new View.OnClickListener() {
             public void onClick(View v) {

                 int index = list.getFirstVisiblePosition();
                 getListView().smoothScrollToPosition(index+1); // For increment. 

}
});

However you need to handle one case, that is if only half or part of the view at the top is visible.

Skynet
  • 7,820
  • 5
  • 44
  • 80
  • I need the scrolling by clicking the button. (ie) pressing up button should scroll one row up like that.. Is my question clear? – AndroidOptimist Sep 04 '13 at 12:53
  • 2
    Yes put one of the above snippets inside the button click listener. Thats it! You will have to increment and decrement a variable which will go in the int position, this increment and decrement should happen on the button click. – Skynet Sep 04 '13 at 12:53
  • Sorry for late reply. I put your above code in button as btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { listView.setSelection(8); } });. But its not working – AndroidOptimist Sep 05 '13 at 03:47
  • @user2734849 consider if your listview size is 10 and listview shows 6 items at time, after (10-6) i.e. after 4 initial setselection it will stop scrolling, since listview shows 6 items all the time and the item will be selected but listview will not scroll, if you want to scroll without selecting the item get the height of each item and use ScrollTO or ScrollBy methods. – bala Sep 05 '13 at 07:02
2

Have you even checked for IDE suggestions? ;)

ListView lv = (ListView) findViewById(R.id.myListView);

// to scroll to a given position
lv.scrollTo(int x, int y);

// to scroll by a given number of dp
lv.scrollBy(int x, int y);
meeDamian
  • 1,143
  • 2
  • 11
  • 24
0

Scroll with smooth Duration

getListView().smoothScrollToPositionFromTop(position,offset,duration);

Parameters position -> Position to scroll to

offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished

duration-> Number of milliseconds to use for the scroll

Note: From API 11.

Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300