Item positioning in Android's ListView

Item positioning in Android's ListView

In the development of Android, we often use the ListView control. The listview can display data in the form of a list, but when we click one of the items to jump and return to this page, we will find the item displayed by the listView at this time The index of is the 0th, and we often locate the item position we clicked when we return.

There are two ways to solve this problem:
1: Use the setSelection() method. Disadvantages: Can't exactly restore to the last browsed location

	//点击item时记录点击的position
	//在onResume方法中设置下面代码即可实现
	listView.setSelection(position);

2: Use the setSelectionFromTop() method. Advantages: It can accurately locate the location of the last browse

	//定义全局的变量用来记录位置
	int index, top;//记录item位置使用
	index = listView1.getFirstVisiblePosition();//获取可见的第一个item位置
    View v = listView1.getChildAt(0);//获取第一个item
    top = (v == null) ? 0 : v.getTop();//获取第一个item相对于其父视图的顶部位置,一般为负数


	//在onResume方法中设置下面代码即可实现
	listView1.setSelectionFromTop(index, top);
    index = 0;top = 0;//清空位置  防止下拉刷新时定位异常

Guess you like

Origin blog.csdn.net/weixin_46139477/article/details/126290354