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);
}
}
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);
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.
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();
}
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);
}
});
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.