listView 这个空间中有很多关于位置变化的方法,
写了一个demo代码如下:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listView = (ListView) findViewById(R.id.listView); String arr[] = new String[]{"猴子", "猴子", "猴子", "猴子", "猴子", "猴子", "猴子"}; listView.setAdapter(new ArrayAdapter<>(this, R.layout.adapter_layout, arr)); final int firstSeePostion = listView.getFirstVisiblePosition(); listView.getLastVisiblePosition() listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final int lastSeePostion = firstSeePostion + listView.getChildCount() ; Toast.makeText(MainActivity.this, "你点击的位置是 " + position + "+" + firstSeePostion + "+" + listView.getHeight() + "+" + listView.getChildAt(position).getBottom() + "+" + listView.getChildCount() + "+" + lastSeePostion, Toast.LENGTH_SHORT).show(); } }); }
点击不同的item 弹出的值:
其中:firstSeePostion 是在屏幕上显示的第一个位置,一般值为0。
listView.getHeight 是指listView 这个控件的高度,
listView.getChildCount 是在ViewGroup 中的子View的个数,也就mChildren[] 中的count,其实这个count 值的大小应该是我们屏幕上能看见的数量,我们比如在屏幕上能看见4个listView 的item,那么listView.getChildCount 的值就是 4 ,listView.getChildAt(position),这个方法中的position 的值的范围在 position > 0 && postion < count lastSeePostion 这个值 mFirstPosition + getChildCount() - 1; 注意这个值的获取,需要在子线程中获取,因为getChildCount 这个值是 直接获取不到的,需要绘制后,才能获取到,所以在用的时候 通过以下的方式获取:
private class ScrollListRunnable implements Runnable { private int mPosition; public ScrollListRunnable(int position) { mPosition = position; } @Override public void run() { int firstVisiblePosition = mOrderQuestionListView.getFirstVisiblePosition(); int lastVisiblePosition = mOrderQuestionListView.getLastVisiblePosition(); if (mPosition >= firstVisiblePosition && mPosition <= lastVisiblePosition) { int childIndex = mPosition - firstVisiblePosition; View child = mOrderQuestionListView.getChildAt(childIndex); int childBottom = child.getBottom(); int listHeight = mOrderQuestionListView.getHeight(); if (childBottom > listHeight) { int newChildTop = listHeight - child.getHeight(); mOrderQuestionListView.smoothScrollToPositionFromTop(mPosition, newChildTop); } } } }
类似这段代码中的方式去实现。