[英]Android listview how to scroll selected item to the top
I am trying to create a ListView in Android. 我想在Android中创建一个ListView。 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
这是我正在尝试的Activity类,项目选择工作正常,但它不会滚动到顶部
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)
. 尝试使用此方法
setSelection (int position)
。
Sets the currently selected item. 设置当前选定的项目。 To support accessibility subclasses that override this method must invoke the
overridden
super method first. 要支持覆盖此方法的可访问性子类,必须首先调用
overridden
超级方法。
According to this https://stackoverflow.com/a/18133295/3225458 , you should try to post
smooth scrolling: 根据这个https://stackoverflow.com/a/18133295/3225458 ,您应该尝试
post
平滑滚动:
@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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.