2

I am trying to create a ListView in Android. When I click on an item, I want it to scroll it over to the top. How can I do that? Here is the Activity class that I am trying out, item selections works fine but it does not scroll over to the top

public class MyListActivity extends ListActivity {
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
        "Linux", "OS/2" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        String item = (String) getListAdapter().getItem(position);
        //l.setSelection(2);

        Toast.makeText(this, position + " selected", Toast.LENGTH_LONG).show();
        //l.smoothScrollToPosition(5);

    }
}
user1892775
  • 1,731
  • 4
  • 31
  • 52

4 Answers4

12

Use this. Will scroll the item in position smoothly to the top of the listview.

int duration = 500;  //miliseconds
int offset = 0;      //fromListTop

listview.smoothScrollToPositionFromTop(position,offset,duration);
  • descrease duration to make scrolling faster
Adam
  • 978
  • 1
  • 8
  • 20
1

Try to use this method setSelection (int position).

Sets the currently selected item. To support accessibility subclasses that override this method must invoke the overridden super method first.

Piyush
  • 24,288
  • 6
  • 40
  • 72
1

According to this https://stackoverflow.com/a/18133295/3225458, you should try to post smooth scrolling:

@Override
protected void onListItemClick(final ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    l.post(new Runnable() {
        @Override
        public void run() {
            l.smoothScrollToPosition(pos);
        }
    });
    Toast.makeText(this, position + " selected", Toast.LENGTH_LONG).show();
}
Community
  • 1
  • 1
romtsn
  • 11,234
  • 2
  • 28
  • 47
0

try this one:-

yourListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                int duration = 500; // miliseconds
                int offset = 0;
                yourListView.smoothScrollToPositionFromTop(arg2, offset, duration);
                yourListView.setSelection(arg2);
            }
        });
SweetWisher ツ
  • 7,288
  • 2
  • 28
  • 70
pRaNaY
  • 23,128
  • 23
  • 90
  • 142